CONTENTS

Chapter 7. Advanced AWT

In Volume 1, you have seen how to use the methods of the Graphics class to create simple drawings. Those methods are sufficient for simple applets and applications, but they fall short for complex shapes or when you require complete control over the appearance of the graphics. The Java 2D API is a more recent class library that you can use to produce high-quality drawings. In this chapter, we give you an overview of that API.

We then turn to the topic of printing and show how you can implement printing capabilities into your programs.

Finally, we cover two techniques for transferring data between programs: the system clipboard and the drag-and-drop mechanism. You can use these techniques to transfer data between two Java applications, or between a Java application and a native program.

The Rendering Pipeline

The original JDK 1.0 had a very simple mechanism for drawing shapes. You select color and paint mode, and call methods of the Graphics class such as drawRect or fillOval. The Java 2D API supports many more options.

To draw a shape, you go through the following steps:

  1. Obtain an object of the Graphics2D class. This class is a subclass of the Graphics class. If you use a version of the JDK that is enabled for Java 2D technology, methods such as paint and paintComponent automatically receive an object of the Graphics2D class. Simply use a cast, as follows:

    public void paintComponent(Graphics g)
    {
       Graphics2D g2 = (Graphics2D)g;
       . . .
    }
    
  2. Use the setRenderingHints method to set rendering hints: trade-offs between speed and drawing quality.

    RenderingHints hints = . . .;
    g2.setRenderingHints(hints);
    
  3. Use the setStroke method to set the stroke. The stroke is used to draw the outline of the shape. You can select the thickness and choose among solid and dotted lines.

    Stroke stroke = . . .;
    g2.setStroke(stroke);
    
  4. Use the setPaint method to set the paint. The paint is used to fill areas such as the stroke path or the interior of a shape. You can create solid color paint, paint with changing hues, or tiled fill patterns.

    Paint paint = . . .;
    g2.setPaint(paint);
    
  5. Use the setClip method to set the clipping region.

    Shape clip = . . .;
    g2.clip(clip);
    
  6. Use the setTransform method to set a transformation from user space to device space. You use transformations if it is easier for you to define your shapes in a custom coordinate system than by using pixel coordinates.

    AffineTransform transform = . . .;
    g2.transform(transform);
    
  7. Use the setComposite method to set a composition rule that describes how to combine the new pixels with the existing pixels.

    Composite composite = . . .;
    g2.setComposite(composite);
    
  8. Create a shape. The Java 2D API supplies many shape objects and methods to combine shapes.

    Shape shape = . . .;
    
  9. Draw or fill the shape. If you draw the shape, its outline is stroked. If you fill the shape, the interior is painted.

    g2.draw(shape);
    g2.fill(shape);
    

Of course, in many practical circumstances, you don't need all these steps. There are reasonable defaults for the settings of the 2D graphics context. You only need to change the settings if you want to change the defaults.

In the following sections, you will see how to describe shapes, strokes, paints, transformations, and composition rules.

The various set methods simply set the state of the 2D graphics context. They don't cause any drawing. Similarly, when you construct Shape objects, no drawing takes place. A shape is only rendered when you call draw or fill. At that time, the new shape is computed in a rendering pipeline (see Figure 7-1).

Figure 7-1. The rendering pipeline

graphics/07fig01.gif

In the rendering pipeline, the following steps take place to render a shape.

  1. The path of the shape is stroked.

  2. The shape is transformed.

  3. The shape is clipped. If there is no intersection between the shape and the clipping area, then the process stops.

  4. The remainder of the shape after clipping is filled.

  5. The pixels of the filled shape are composed with the existing pixels.(In Figure 7-1, the circle is part of the existing pixels, and the cup shape is superimposed over it.)

In the next section, you will see how to define shapes. Then, we turn to the 2D graphics context settings.

java.awt.Graphics2D

graphics/api.gif
 

Shapes

Here are some of the methods in the Graphics class to draw shapes:

drawLine
drawRectangle
drawRoundRect
draw3DRect
drawPolygon
drawPolyline
drawOval
drawArc

There are also corresponding fill methods. These methods have been in the Graphics class ever since JDK 1.0. The Java 2D API uses a completely different, object-oriented approach. Instead of methods, there are classes:

Line2D
Rectangle2D
RoundRectangle2D
Ellipse2D
Arc2D
QuadCurve2D
CubicCurve2D
GeneralPath

These classes all implement the Shape interface.

Finally, there is a Point2D class that describes a point with an x- and a y-coordinate. Points are useful to define shapes, but they aren't themselves shapes.

To draw a shape, you first create an object of a class that implements the Shape interface and then call the draw method of the Graphics2D class.

The Line2D, Rectangle2D, RoundRectangle2D, Ellipse2D, and Arc2D classes correspond to the drawLine, drawRectangle, drawRoundRect, drawOval, and drawArc methods. (The concept of a "3D rectangle" has died the death that it so richly deserved—there is no analog to the draw3DRect method.) The Java 2D API supplies two additional classes: quadratic and cubic curves. We discuss these shapes later in this section. There is no Polygon2D class. Instead, the GeneralPath class describes paths that are made up from lines, quadratic and cubic curves. You can use a GeneralPath to describe a polygon; we show you how later in this section.

The classes

Rectangle2D
RoundRectangle2D
Ellipse2D
Arc2D

all inherit from a common superclass RectangularShape. Admittedly, ellipses and arcs are not rectangular, but they have a bounding rectangle (see Figure 7-2).

Figure 7-2. The bounding rectangle of an ellipse and an arc

graphics/07fig02.gif

Each of the classes whose name ends in "2D" has two subclasses for specifying coordinates as float or double quantities. In Volume 1, you already encountered

Rectangle2D.Float
Rectangle2D.Double

The same scheme is used for the other classes, such as

Arc2D.Float
Arc2D.Double

Internally, all graphics classes use float coordinates since float numbers use less storage space, and they have sufficient precision for geometric computations. However, the Java programming language makes it a bit more tedious to manipulate float numbers. For that reason, most methods of the graphics classes use double parameters and return values. Only when constructing a 2D object, you need to choose between a constructor with float or double coordinates. For example,

Rectangle2D floatRect
   = new Rectangle2D.Float(5F, 10F, 7.5F, 15F);
Rectangle2D doubleRect
   = new Rectangle2D.Double(5, 10, 7.5, 15);

The Xxx2D.Float and Xxx2D.Double classes are subclasses of the Xxx2D classes. After object construction, there is essentially no benefit in remembering the subclass, and you can just store the constructed object in a superclass variable, just like in the code example.

As you can see from the curious names, the Xxx2D.Float and Xxx2D.Double classes are also inner classes of the Xxx2D classes. That is just a minor syntactical convenience, to avoid an inflation of outer class names.

Figure 7-3 shows the relationships between the shape classes. However, the Double and Float subclasses are omitted. Legacy classes from the pre-2D library are marked with a gray fill.

Figure 7-3. Relationships between the shape classes

graphics/07fig03.gif

Using the Shape Classes

You already saw how to use the Rectangle2D, Ellipse2D, and Line2D classes in Chapter 7 of Volume 1. In this section, you will learn how to work with the remaining 2D shapes.

For the RoundRectangle2D shape, you specify the top left corner, width and height, and the x- and y-dimension of the corner area that should be rounded (see Figure 7-4). For example, the call

Figure 7-4. Constructing a RoundRectangle2D

graphics/07fig04.gif

RoundRectangle2D r = new RoundRectangle2D.Double(150, 200,
   100, 50, 20, 20);

produces a rounded rectangle with circles of radius 20 at each of the corners.

To construct an arc, you specify the bounding box, followed by the start angle and the angle swept out by the arc (see Figure 7-5) and the closure type, one of Arc2D.OPEN, Arc2D.PIE, or Arc2D.CHORD.

Figure 7-5. Constructing an elliptical arc

graphics/07fig05.gif

Arc2D a = new Arc2D(x, y, width, height,
   startAngle, arcAngle, closureType);

Figure 7-6 illustrates the arc types.

Figure 7-6. Arc types

graphics/07fig06.gif

However, the angles are not simply given in degrees, but they are distorted such that a 45-degree angle denotes the diagonal position, even if width and height are not the same. If you draw circular arcs (for example in a pie chart), then you don't need to worry about this. However, for elliptical arcs, be prepared for an adventure in trigonometry—see the sidebar for details.

The Java 2D package supplies quadratic and cubic curves. In this chapter, we do not want to get into the mathematics of these curves. We suggest you get a feel for how the curves look by running the program in Example 7-1. As you can see in Figures 7-7 and 7-8, quadratic and cubic curves are specified by two end points and one or two control points. Moving the control points changes the shape of the curves.

Figure 7-7. A quadratic curve

graphics/07fig07.gif

Figure 7-8. A cubic curve

graphics/07fig08.gif

Specifying Angles for Elliptical Arcs

The algorithm for drawing elliptical arcs uses distorted angles, which the caller must precompute. This sidebar tells you how. If you belong to the large majority of programmers who never draw elliptical arcs, just skip the sidebar. However, since the official documentation completely glosses over this topic, we thought it is worth recording it to save those who need this information a few hours of trigonometric agony.

You convert actual angles to distorted angles with the following formula.

distortedAngle = Math.atan2(Math.sin(angle) * width,
   Math.cos(angle) * height);

Sometimes (such as in the example program at the end of this section), you know an end point of the arc, or another point on the line joining the center of the ellipse and that end point. In that case, first compute

dx = p.getX() - center.getX();
dy = p.getY() - center.getY();

Then, the distorted angle is

distortedAngle = Math.atan2(-dy * width, dx * height);

(The minus sign in front of dy is necessary because in the pixel coordinate system, the y-axis points downwards, which leads to angle measurements that are clockwise, but you need to supply an angle that is measured counterclockwise.)

Convert the result from radians to degrees:

distortedAngle = Math.toDegrees(distortedAngle);

The result is a value between –180 and 180.

Compute both the distorted start and end angles in this way. Then, compute the difference between the two distorted angles.

If either the start angle or the difference is negative, add 360. Then, supply the start angle and the angle difference to the arc constructor.

Arc2D a = new Arc2D(x, y, width, height,
   distortedStartAngle, distortedAngleDifference,
   closureType);

Not only is the documentation vague on the exact nature of the distortion, it is also quite misleading in calling the distorted angle difference value the "arc angle." Except for the case of a circular arc, that value is neither the actual arc angle nor its distortion.

If you run the example program at the end of this section, then you can visually check that this calculation yields the correct values for the arc constructor (see Figure 7-9).

Figure 7-9. The ShapeTest program

graphics/07fig09.gif
 

To construct quadratic and cubic curves, you give the coordinates of the end points and the control points. For example,

QuadCurve2D q = new QuadCurve2D.Double(startX, startY,
   controlX, controlY, endX, endY);
CubicCurve2D c = new CubicCurve2D.Double(startX, startY,
   control1X, control1Y, control2X, control2Y, endX, endY);

Quadratic curves are not very flexible, and they are not commonly used in practice. Cubic curves (such as the Bezier curves drawn by the CubicCurve3D class) are, however, very common. By combining many cubic curves so that the slopes at the connection points match, you can create complex smooth-looking curved shapes. For more information, we refer you to Computer Graphics: Principles and Practice, Second Edition in C by James D. Foley, Andries van Dam, Steven K. Feiner, et al. [Addison Wesley 1995].

You can build arbitrary sequences of line segments, quadratic curves, and cubic curves, and store them in a GeneralPath object. You specify the first coordinate of the path with the moveTo method. For example,

GeneralPath path = new GeneralPath();
path.moveTo(10, 20);

Then, you extend the path by calling one of the methods lineTo, quadTo, or curveTo. These methods extend the path by a line, a quadratic curve, or a cubic curve. To call lineTo, supply the end point. For the two curve methods, supply the control points, then the end point. For example,

path.lineTo(20, 30);
path.curveTo(control1X, control1Y, control2X, control2Y, endX, endY);

You can close the path by calling the closePath method. It draws a line back to the last moveTo.

To make a polygon, simply call moveTo to go to the first corner point, followed by repeated calls to lineTo to visit the other corner points. Finally, call closePath to close the polygon. The program in Example 7-1 shows this in more detail.

A general path does not have to be connected. You can call moveTo at any time to start a new path segment.

Finally, you can use the append method to add arbitrary Shape objects to a general path. The outline of the shape is added to the end to the path. The second parameter of the append method is true if the new shape should be connected to the last point on the path, false if it should not be connected. For example, the call

Rectangle2D r = . . .;
path.append(r, false);

appends the outline of a rectangle to the path without connecting it to the existing path. But

path.append(r, true);

adds a straight line from the end point of the path to the starting point of the rectangle, and then adds the rectangle outline to the path.

The program in Example 7-1 lets you create sample paths. Figures 7-7 and 7-8 show sample runs of the program. You pick a shape maker from the combo box. The program contains shape makers for

Use the mouse to adjust the control points. As you move them, the shape continuously repaints itself.

The program is a bit complex because it handles a multiplicity of shapes and it supports dragging of the control points.

An abstract superclass ShapeMaker encapsulates the commonality of the shape maker classes. Each shape has a fixed number of control points that the user can move around. The getPointCount method returns that value. The abstract method

Shape makeShape(Point2D[] points)

computes the actual shape, given the current positions of the control points. The toString method returns the class name so that the ShapeMaker objects can simply be dumped into a JComboBox.

To enable dragging of the control points, the ShapePanel class handles both mouse and mouse motion events. If the mouse is pressed on top of a rectangle, subsequent mouse drags move the rectangle.

The majority of the shape maker classes are simple—their makeShape methods just construct and return the requested shape. However, the ArcMaker class needs to compute the distorted start and end angles. Furthermore, to demonstrate that the computation is indeed correct, the returned shape is a GeneralPath containing the arc itself, the bounding rectangle, and the lines from the center of the arc to the angle control points (see Figure 7-9).

Example 7-1 ShapeTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program demonstrates the various 2D shapes.
  9. */
 10. public class ShapeTest
 11. {
 12.    public static void main(String[] args)
 13.    {
 14.       JFrame frame = new ShapeTestFrame();
 15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 16.       frame.show();
 17.    }
 18. }
 19.
 20. /**
 21.    This frame contains a combo box to select a shape
 22.    and a panel to draw it.
 23. */
 24. class ShapeTestFrame extends JFrame
 25. {
 26.    public ShapeTestFrame()
 27.    {
 28.       setTitle("ShapeTest");
 29.       setSize(WIDTH, HEIGHT);
 30.
 31.       Container contentPane = getContentPane();
 32.
 33.       final ShapePanel panel = new ShapePanel();
 34.       contentPane.add(panel, BorderLayout.CENTER);
 35.       final JComboBox comboBox = new JComboBox();
 36.       comboBox.addItem(new LineMaker());
 37.       comboBox.addItem(new RectangleMaker());
 38.       comboBox.addItem(new RoundRectangleMaker());
 39.       comboBox.addItem(new EllipseMaker());
 40.       comboBox.addItem(new ArcMaker());
 41.       comboBox.addItem(new PolygonMaker());
 42.       comboBox.addItem(new QuadCurveMaker());
 43.       comboBox.addItem(new CubicCurveMaker());
 44.       comboBox.addActionListener(new
 45.          ActionListener()
 46.          {
 47.             public void actionPerformed(ActionEvent event)
 48.             {
 49.                ShapeMaker shapeMaker =
 50.                   (ShapeMaker)comboBox.getSelectedItem();
 51.                panel.setShapeMaker(shapeMaker);
 52.             }
 53.          });
 54.       contentPane.add(comboBox, BorderLayout.NORTH);
 55.    }
 56.
 57.    private static final int WIDTH = 300;
 58.    private static final int HEIGHT = 300;
 59. }
 60.
 61. /**
 62.    This panel draws a shape and allows the user to
 63.    move the points that define it.
 64. */
 65. class ShapePanel extends JPanel
 66. {
 67.    public ShapePanel()
 68.    {
 69.       addMouseListener(new
 70.          MouseAdapter()
 71.          {
 72.             public void mousePressed(MouseEvent event)
 73.             {
 74.                Point p = event.getPoint();
 75.                for (int i = 0; i < points.length; i++)
 76.                {
 77.                   double x = points[i].getX() - SIZE / 2;
 78.                   double y = points[i].getY() - SIZE / 2;
 79.                   Rectangle2D r
 80.                      = new Rectangle2D.Double(x, y, SIZE, SIZE);
 81.                   if (r.contains(p))
 82.                   {
 83.                      current = i;
 84.                      return;
 85.                   }
 86.                }
 87.             }
 88.
 89.             public void mouseReleased(MouseEvent event)
 90.             {
 91.                current = -1;
 92.             }
 93.          });
 94.       addMouseMotionListener(new
 95.          MouseMotionAdapter()
 96.          {
 97.             public void mouseDragged(MouseEvent event)
 98.             {
 99.                if (current == -1) return;
100.                points[current] = event.getPoint();
101.                repaint();
102.             }
103.          });
104.       current = -1;
105.    }
106.
107.    /**
108.       Set a shape maker and initialize it with a random
109.       point set.
110.       @param aShapeMaker a shape maker that defines a shape
111.       from a point set
112.    */
113.    public void setShapeMaker(ShapeMaker aShapeMaker)
114.    {
115.       shapeMaker = aShapeMaker;
116.       int n = shapeMaker.getPointCount();
117.       points = new Point2D[n];
118.       for (int i = 0; i < n; i++)
119.       {
120.          double x = generator.nextDouble() * getWidth();
121.          double y = generator.nextDouble() * getHeight();
122.          points[i] = new Point2D.Double(x, y);
123.       }
124.       repaint();
125.    }
126.
127.    public void paintComponent(Graphics g)
128.    {
129.       super.paintComponent(g);
130.       if (points == null) return;
131.       Graphics2D g2 = (Graphics2D)g;
132.       for (int i = 0; i < points.length; i++)
133.       {  double x = points[i].getX() - SIZE / 2;
134.          double y = points[i].getY() - SIZE / 2;
135.          g2.fill(new Rectangle2D.Double(x, y, SIZE, SIZE));
136.       }
137.
138.       g2.draw(shapeMaker.makeShape(points));
139.    }
140.
141.    private Point2D[] points;
142.    private static Random generator = new Random();
143.    private static int SIZE = 10;
144.    private int current;
145.    private ShapeMaker shapeMaker;
146. }
147.
148. /**
149.    A shape maker can make a shape from a point set.
150.    Concrete subclasses must return a shape in the makeShape
151.    method.
152. */
153. abstract class ShapeMaker
154. {
155.    /**
156.       Constructs a shape maker.
157.       @param aPointCount the number of points needed to define
158.       this shape.
159.    */
160.    public ShapeMaker(int aPointCount)
161.    {
162.       pointCount = aPointCount;
163.    }
164.
165.    /**
166.       Gets the number of points needed to define this shape.
167.       @return the point count
168.    */
169.    public int getPointCount()
170.    {
171.       return pointCount;
172.    }
173.
174.    /**
175.       Makes a shape out of the given point set.
176.       @param p the points that define the shape
177.       @return the shape defined by the points
178.    */
179.    public abstract Shape makeShape(Point2D[] p);
180.
181.    public String toString()
182.    {
183.       return getClass().getName();
184.    }
185.
186.    private int pointCount;
187. }
188.
189. /**
190.    Makes a line that joins two given points.
191. */
192. class LineMaker extends ShapeMaker
193. {
194.    public LineMaker() { super(2); }
195.
196.    public Shape makeShape(Point2D[] p)
197.    {
198.       return new Line2D.Double(p[0], p[1]);
199.    }
200. }
201.
202. /**
203.    Makes a line that joins two given corner points.
204. */
205. class RectangleMaker extends ShapeMaker
206. {
207.    public RectangleMaker() { super(2); }
208.
209.    public Shape makeShape(Point2D[] p)
210.    {
211.       Rectangle2D s = new Rectangle2D.Double();
212.       s.setFrameFromDiagonal(p[0], p[1]);
213.       return s;
214.    }
215. }
216.
217. /**
218.    Makes a round rectangle that joins two given corner points.
219. */
220. class RoundRectangleMaker extends ShapeMaker
221. {
222.    public RoundRectangleMaker() { super(2); }
223.
224.    public Shape makeShape(Point2D[] p)
225.    {
226.       RoundRectangle2D s
227.          = new RoundRectangle2D.Double(0, 0, 0, 0, 20, 20);
228.       s.setFrameFromDiagonal(p[0], p[1]);
229.       return s;
230.    }
231. }
232.
233. /**
234.    Makes an ellipse contained in a bounding box with two given
235.    corner points.
236. */
237. class EllipseMaker extends ShapeMaker
238. {
239.    public EllipseMaker() { super(2); }
240.
241.    public Shape makeShape(Point2D[] p)
242.    {
243.       Ellipse2D s = new Ellipse2D.Double();
244.       s.setFrameFromDiagonal(p[0], p[1]);
245.       return s;
246.    }
247. }
248.
249. /**
250.    Makes an arc contained in a bounding box with two given
251.    corner points, and with starting and ending angles given
252.    by lines emanating from the center of the bounding box and
253.    ending in two given points. To show the correctness of
254.    the angle computation, the returned shape contains the arc,
255.    the bounding box, and the lines.
256. */
257. class ArcMaker extends ShapeMaker
258. {
259.    public ArcMaker() { super(4); }
260.
261.    public Shape makeShape(Point2D[] p)
262.    {
263.       double centerX = (p[0].getX() + p[1].getX()) / 2;
264.       double centerY = (p[0].getY() + p[1].getY()) / 2;
265.       double width = Math.abs(p[1].getX() - p[0].getX());
266.       double height = Math.abs(p[1].getY() - p[0].getY());
267.
268.       double distortedStartAngle
269.          = Math.toDegrees(Math.atan2(-(p[2].getY() - centerY)
270.             * width, (p[2].getX() - centerX) * height));
271.       double distortedEndAngle
272.          = Math.toDegrees(Math.atan2(-(p[3].getY() - centerY)
273.             * width, (p[3].getX() - centerX) * height));
274.       double distortedAngleDifference
275.          = distortedEndAngle - distortedStartAngle;
276.       if (distortedStartAngle < 0)
277.          distortedStartAngle += 360;
278.       if (distortedAngleDifference < 0)
279.          distortedAngleDifference += 360;
280.
281.       Arc2D s = new Arc2D.Double(0, 0, 0, 0,
282.          distortedStartAngle, distortedAngleDifference,
283.          Arc2D.OPEN);
284.       s.setFrameFromDiagonal(p[0], p[1]);
285.
286.       GeneralPath g = new GeneralPath();
287.       g.append(s, false);
288.       Rectangle2D r = new Rectangle2D.Double();
289.       r.setFrameFromDiagonal(p[0], p[1]);
290.       g.append(r, false);
291.       Point2D center = new Point2D.Double(centerX, centerY);
292.       g.append(new Line2D.Double(center, p[2]), false);
293.       g.append(new Line2D.Double(center, p[3]), false);
294.       return g;
295.    }
296. }
297.
298. /**
299.    Makes a polygon defined by six corner points.
300. */
301. class PolygonMaker extends ShapeMaker
302. {
303.    public PolygonMaker() { super(6); }
304.
305.    public Shape makeShape(Point2D[] p)
306.    {
307.       GeneralPath s = new GeneralPath();
308.       s.moveTo((float)p[0].getX(), (float)p[0].getY());
309.       for (int i = 1; i < p.length; i++)
310.          s.lineTo((float)p[i].getX(), (float)p[i].getY());
311.       s.closePath();
312.       return s;
313.    }
314. }
315.
316. /**
317.    Makes a quad curve defined by two end points and a control
318.    point.
319. */
320. class QuadCurveMaker extends ShapeMaker
321. {
322.    public QuadCurveMaker() { super(3); }
323.
324.    public Shape makeShape(Point2D[] p)
325.    {
326.       return new QuadCurve2D.Double(p[0].getX(), p[0].getY(),
327.          p[1].getX(), p[1].getY(), p[2].getX(), p[2].getY());
328.    }
329. }
330.
331. /**
332.    Makes a cubic curve defined by two end points and two control
333.    points.
334. */
335. class CubicCurveMaker extends ShapeMaker
336. {
337.    public CubicCurveMaker() { super(4); }
338.
339.    public Shape makeShape(Point2D[] p)
340.    {
341.       return new CubicCurve2D.Double(p[0].getX(), p[0].getY(),
342.          p[1].getX(), p[1].getY(), p[2].getX(), p[2].getY(),
343.          p[3].getX(), p[3].getY());
344.    }
java.awt.geom.RoundRectangle2D.Double

graphics/api.gif
 

java.awt.geom.Arc2D.Double

graphics/api.gif
 

java.awt.geom.QuadCurve2D.Double

graphics/api.gif
 

java.awt.geom.CubicCurve2D.Double

graphics/api.gif
 

java.awt.geom.GeneralPath

graphics/api.gif
 

Areas

In the preceding section, you saw how you can specify complex shapes by constructing general paths that are composed of lines and curves. By using a sufficient number of lines and curves, you can draw essentially any shape. For example, the shapes of characters in the fonts that you see on the screen and on your printouts are all made up of lines and cubic curves.

However, occasionally, it is easier to describe a shape by composing it from areas, such as rectangles, polygons, or ellipses. The Java 2D API supports four constructive area geometry operations that combine two areas to a new area:

Figure 7-10 shows these operations.

Figure 7-10. Constructive Area Geometry Operations

graphics/07fig10.gif

To construct a complex area, you start out with a default area object.

Area a = new Area();

Then, you combine the area with any shape:

a.add(new Rectangle2D.Double(. . .));
a.subtract(path);
. . .

The Area class implements the Shape interface. You can stroke the boundary of the area with the draw method or paint the interior with the fill method of the Graphics2D class.

The program in Example 7-2 shows the constructive area geometry operations. Select one of the four operations, and see the result of combining an ellipse and a rectangle with the operation that you selected (see Figure 7-11).

Figure 7-11. The AreaTest Program

graphics/07fig11.gif

Example 7-2 AreaTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program demonstrates constructive area geometry
  9.    operations.
 10. */
 11. public class AreaTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new AreaTestFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19. }
 20.
 21. /**
 22.    This frame contains a set of radio buttons to define
 23.    area operations and a panel to show their result.
 24. */
 25. class AreaTestFrame extends JFrame
 26. {
 27.    public AreaTestFrame()
 28.    {
 29.       setTitle("AreaTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       area1
 33.          = new Area(new Ellipse2D.Double(100, 100, 150, 100));
 34.       area2
 35.          = new Area(new Rectangle2D.Double(150, 150, 150, 100));
 36.
 37.       Container contentPane = getContentPane();
 38.       panel = new
 39.          JPanel()
 40.          {
 41.             public void paintComponent(Graphics g)
 42.             {
 43.                super.paintComponent(g);
 44.                Graphics2D g2 = (Graphics2D)g;
 45.                g2.draw(area1);
 46.                g2.draw(area2);
 47.                if (area != null) g2.fill(area);
 48.             }
 49.          };
 50.
 51.       contentPane.add(panel, BorderLayout.CENTER);
 52.
 53.       JPanel buttonPanel = new JPanel();
 54.       ButtonGroup group = new ButtonGroup();
 55.
 56.       JRadioButton addButton = new JRadioButton("Add", false);
 57.       buttonPanel.add(addButton);
 58.       group.add(addButton);
 59.       addButton.addActionListener(new
 60.          ActionListener()
 61.          {
 62.             public void actionPerformed(ActionEvent event)
 63.             {
 64.                area = new Area();
 65.                area.add(area1);
 66.                area.add(area2);
 67.                panel.repaint();
 68.             }
 69.          });
 70.
 71.       JRadioButton subtractButton
 72.          = new JRadioButton("Subtract", false);
 73.       buttonPanel.add(subtractButton);
 74.       group.add(subtractButton);
 75.       subtractButton.addActionListener(new
 76.          ActionListener()
 77.          {
 78.             public void actionPerformed(ActionEvent event)
 79.             {
 80.                area = new Area();
 81.                area.add(area1);
 82.                area.subtract(area2);
 83.                panel.repaint();
 84.             }
 85.          });
 86.
 87.       JRadioButton intersectButton
 88.          = new JRadioButton("Intersect", false);
 89.       buttonPanel.add(intersectButton);
 90.       group.add(intersectButton);
 91.       intersectButton.addActionListener(new
 92.          ActionListener()
 93.          {
 94.             public void actionPerformed(ActionEvent event)
 95.             {
 96.                area = new Area();
 97.                area.add(area1);
 98.                area.intersect(area2);
 99.                panel.repaint();
100.             }
101.          });
102.
103.       JRadioButton exclusiveOrButton
104.          = new JRadioButton("Exclusive Or", false);
105.       buttonPanel.add(exclusiveOrButton);
106.       group.add(exclusiveOrButton);
107.       exclusiveOrButton.addActionListener(new
108.          ActionListener()
109.          {
110.             public void actionPerformed(ActionEvent event)
111.             {
112.                area = new Area();
113.                area.add(area1);
114.                area.exclusiveOr(area2);
115.                panel.repaint();
116.             }
117.          });
118.
119.       contentPane.add(buttonPanel, BorderLayout.NORTH);
120.    }
121.
122.    private JPanel panel;
123.    private Area area;
124.    private Area area1;
125.    private Area area2;
126.
127.    private static final int WIDTH = 400;
128.    private static final int HEIGHT = 400;
129. }

java.awt.geom.Area

graphics/api.gif
 

Strokes

The draw operation of the Graphics2D class draws the boundary of a shape by using the currently selected stroke. By default, the stroke is a solid line that is one pixel wide. You can select a different stroke by calling the setStroke method. You supply an object of a class that implements the Stroke interface. The Java 2D API defines only one such class, called BasicStroke. In this section, we look at the capabilities of the BasicStroke class.

You can construct strokes of arbitrary thickness. For example, here is how you draw lines that are 10 pixels wide.

g2.setStroke(new BasicStroke(10.0F));
g2.draw(new Line2D.Double(. . .));

When a stroke is more than a pixel thick, then the end of the stroke can have different styles. Figure 7-12 shows these so-called end cap styles. There are three choices:

Figure 7-12. End Cap Styles

graphics/07fig12.gif

When two thick strokes meet, there are three choices for the join style (see Figure 7-13).

Figure 7-13. Join Styles

graphics/07fig13.gif

The miter join is not suitable for lines that meet at small angles. If two lines join with an angle that is less than the miter limit, then a bevel join is used instead. That usage prevents extremely long spikes. By default, the miter limit is ten degrees.

You specify these choices in the BasicStroke constructor, for example:

g2.setStroke(new BasicStroke(10.0F, BasicStroke.CAP_ROUND,
   BasicStroke.JOIN_ROUND));
g2.setStroke(new BasicStroke(10.0F, BasicStroke.CAP_BUTT,
   BasicStroke.JOIN_MITER, 15.0F /* miter limit */));

Finally, you can specify dashed lines by setting a dash pattern. In the program in Example 7-3, you can select a dash pattern that spells out SOS in Morse code. The dash pattern is a float[] array of numbers that contains the lengths of the "on" and "off" strokes (see Figure 7-14).

Figure 7-14. A dash pattern

graphics/07fig14.gif

You specify the dash pattern and a dash phase when constructing the BasicStroke. The dash phase indicates where in the dash pattern each line should start. Normally, you set this value to 0.

float[] dashPattern
   = { 10, 10, 10, 10, 10, 10, 30, 10, 30, ... };
g2.setStroke(new BasicStroke(10.0F, BasicStroke.CAP_BUTT,
   BasicStroke.JOIN_MITER, 10.0F /* miter limit */,
   dashPattern, 0 /* dash phase */));

NOTE

graphics/note.gif
 

End cap styles are applied to the ends of each dash in a dash pattern.

The program in Example 7-3 lets you specify end cap styles, join styles, and dashed lines (see Figure 7-15). You can move the ends of the line segments to test out the miter limit: select the miter join, then move the line segment to form a very acute angle. You will see the miter join turn into a bevel join.

Figure 7-15. The StrokeTest program

graphics/07fig15.gif

The program is similar to the program in Example 7-1. The mouse listener remembers if you click on the end point of a line segment, and the mouse motion listener monitors the dragging of the end point. A set of radio buttons signal the user choices for the end cap style, join style, and solid or dashed line. The paintComponent method of the StrokePanel class constructs a GeneralPath consisting of the two line segments that join the three points that the user can move with the mouse. It then constructs a BasicStroke, according to the selections that the user made, and finally draws the path.

Example 7-3 StrokeTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program demonstrates different stroke types.
  9. */
 10. public class StrokeTest
 11. {
 12.    public static void main(String[] args)
 13.    {
 14.       JFrame frame = new StrokeTestFrame();
 15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 16.       frame.show();
 17.    }
 18. }
 19.
 20. /**
 21.    This frame lets the user choose the cap, join, and
 22.    line style, and shows the resulting stroke.
 23. */
 24. class StrokeTestFrame extends JFrame
 25. {
 26.    public StrokeTestFrame()
 27.    {
 28.       setTitle("StrokeTest");
 29.       setSize(WIDTH, HEIGHT);
 30.
 31.       Container contentPane = getContentPane();
 32.       canvas = new StrokePanel();
 33.       contentPane.add(canvas, BorderLayout.CENTER);
 34.
 35.       buttonPanel = new JPanel();
 36.       buttonPanel.setLayout(new GridLayout(3, 3));
 37.       contentPane.add(buttonPanel, BorderLayout.NORTH);
 38.
 39.       ButtonGroup group1 = new ButtonGroup();
 40.       makeCapButton("Butt Cap", BasicStroke.CAP_BUTT, group1);
 41.       makeCapButton("Round Cap", BasicStroke.CAP_ROUND, group1);
 42.       makeCapButton("Square Cap", BasicStroke.CAP_SQUARE,
 43.          group1);
 44.
 45.       ButtonGroup group2 = new ButtonGroup();
 46.       makeJoinButton("Bevel Join", BasicStroke.JOIN_BEVEL,
 47.          group2);
 48.       makeJoinButton("Miter Join", BasicStroke.JOIN_MITER,
 49.          group2);
 50.       makeJoinButton("Round Join", BasicStroke.JOIN_ROUND,
 51.          group2);
 52.
 53.       ButtonGroup group3 = new ButtonGroup();
 54.       makeDashButton("Solid Line", false, group3);
 55.       makeDashButton("Dashed Line", true, group3);
 56.    }
 57.
 58.    /**
 59.       Makes a radio button to change the cap style.
 60.       @param label the button label
 61.       @param style the cap style
 62.       @param group the radio button group
 63.    */
 64.    private void makeCapButton(String label, final int style,
 65.       ButtonGroup group)
 66.    {
 67.       // select first button in group
 68.       boolean selected = group.getButtonCount() == 0;
 69.       JRadioButton button = new JRadioButton(label, selected);
 70.       buttonPanel.add(button);
 71.       group.add(button);
 72.       button.addActionListener(new
 73.          ActionListener()
 74.          {
 75.             public void actionPerformed(ActionEvent event)
 76.             {
 77.                canvas.setCap(style);
 78.             }
 79.          });
 80.    }
 81.
 82.    /**
 83.       Makes a radio button to change the join style.
 84.       @param label the button label
 85.       @param style the join style
 86.       @param group the radio button group
 87.    */
 88.    private void makeJoinButton(String label, final int style,
 89.       ButtonGroup group)
 90.    {
 91.       // select first button in group
 92.       boolean selected = group.getButtonCount() == 0;
 93.       JRadioButton button = new JRadioButton(label, selected);
 94.       buttonPanel.add(button);
 95.       group.add(button);
 96.       button.addActionListener(new
 97.          ActionListener()
 98.          {
 99.             public void actionPerformed(ActionEvent event)
100.             {
101.                canvas.setJoin(style);
102.             }
103.          });
104.    }
105.
106.    /**
107.       Makes a radio button to set solid or dashed lines
108.       @param label the button label
109.       @param style false for solid, true for dashed lines
110.       @param group the radio button group
111.    */
112.    private void makeDashButton(String label, final boolean style,
113.       ButtonGroup group)
114.    {
115.       // select first button in group
116.       boolean selected = group.getButtonCount() == 0;
117.       JRadioButton button = new JRadioButton(label, selected);
118.       buttonPanel.add(button);
119.       group.add(button);
120.       button.addActionListener(new
121.          ActionListener()
122.          {
123.             public void actionPerformed(ActionEvent event)
124.             {
125.                canvas.setDash(style);
126.             }
127.          });
128.    }
129.
130.    private StrokePanel canvas;
131.    private JPanel buttonPanel;
132.
133.    private static final int WIDTH = 400;
134.    private static final int HEIGHT = 400;
135. }
136.
137. /**
138.    This panel draws two joined lines, using different
139.    stroke objects, and allows the user to drag the three
140.    points defining the lines.
141. */
142. class StrokePanel extends JPanel
143. {
144.    public StrokePanel()
145.    {
146.       addMouseListener(new
147.          MouseAdapter()
148.          {
149.             public void mousePressed(MouseEvent event)
150.             {
151.                Point p = event.getPoint();
152.                for (int i = 0; i < points.length; i++)
153.                {
154.                   double x = points[i].getX() - SIZE / 2;
155.                   double y = points[i].getY() - SIZE / 2;
156.                   Rectangle2D r
157.                      = new Rectangle2D.Double(x, y, SIZE, SIZE);
158.                   if (r.contains(p))
159.                   {
160.                      current = i;
161.                      return;
162.                   }
163.                }
164.             }
165.
166.             public void mouseReleased(MouseEvent event)
167.             {
168.                current = -1;
169.             }
170.          });
171.
172.       addMouseMotionListener(new
173.          MouseMotionAdapter()
174.          {
175.             public void mouseDragged(MouseEvent event)
176.             {
177.                if (current == -1) return;
178.                points[current] = event.getPoint();
179.                repaint();
180.             }
181.          });
182.
183.       points = new Point2D[3];
184.       points[0] = new Point2D.Double(200, 100);
185.       points[1] = new Point2D.Double(100, 200);
186.       points[2] = new Point2D.Double(200, 200);
187.       current = -1;
188.       width = 10.0F;
189.    }
190.
191.    public void paintComponent(Graphics g)
192.    {
193.       super.paintComponent(g);
194.       Graphics2D g2 = (Graphics2D)g;
195.       GeneralPath path = new GeneralPath();
196.       path.moveTo((float)points[0].getX(),
197.          (float)points[0].getY());
198.       for (int i = 1; i < points.length; i++)
199.          path.lineTo((float)points[i].getX(),
200.             (float)points[i].getY());
201.       BasicStroke stroke;
202.       if (dash)
203.       {
204.          float miterLimit = 10.0F;
205.          float[] dashPattern = { 10F, 10F, 10F, 10F, 10F, 10F,
206.             30F, 10F, 30F, 10F, 30F, 10F,
207.             10F, 10F, 10F, 10F, 10F, 30F };
208.          float dashPhase = 0;
209.          stroke = new BasicStroke(width, cap, join,
210.             miterLimit, dashPattern, dashPhase);
211.       }
212.       else
213.          stroke = new BasicStroke(width, cap, join);
214.       g2.setStroke(stroke);
215.       g2.draw(path);
216.    }
217.
218.    /**
219.       Sets the join style.
220.       @param j the join style
221.    */
222.    public void setJoin(int j)
223.    {
224.       join = j;
225.       repaint();
226.    }
227.
228.    /**
229.       Sets the cap style.
230.       @param c the cap style
231.    */
232.    public void setCap(int c)
233.    {
234.       cap = c;
235.       repaint();
236.    }
237.
238.    /**
239.       Sets solid or dashed lines
240.       @param d false for solid, true for dashed lines
241.    */
242.    public void setDash(boolean d)
243.    {
244.       dash = d;
245.       repaint();
246.    }
247.
248.    private Point2D[] points;
249.    private static int SIZE = 10;
250.    private int current;
251.    private float width;
252.    private int cap;
253.    private int join;
254.    private boolean dash;
255. }

java.awt.Graphics2D

graphics/api.gif
 

java.awt.BasicStroke

graphics/api.gif
 

Paint

When you fill a shape, its inside is covered with paint. You use the setPaint method to set the paint style to an object whose class implements the Paint interface. In the Java 2D API, there are three such classes:

You construct a GradientPaint object by giving two points and the colors that you want at these two points.

g2.setPaint(new GradientPaint(p1, Color.red, p2, Color.blue));

Colors are interpolated along the line joining the two points. Colors are constant along lines that are perpendicular to that joining line. Points beyond an end point of the line are given the color at the end point.

Alternatively, if you call the GradientPaint constructor with true for the cyclic parameter,

g2.setPaint(new GradientPaint(p1, Color.red, p2, Color.blue, true));

then the color variation cycles and keeps varying beyond the end points.

To construct a TexturePaint object, you need to specify a BufferedImage and an anchor rectangle. The anchor rectangle is extended indefinitely in x- and y-directions to tile the entire coordinate plane. The image is scaled to fit into the anchor and then replicated into each tile.

We will introduce the BufferedImage class later in this chapter when we discuss images in detail. You create a BufferedImage object by giving the image size and the image type. The most common image type is TYPE_INT_ARGB, in which each pixel is specified by an integer that describes the alpha or transparency, red, green, and blue values. For example,

BufferedImage bufferedImage = new BufferedImage(width, height,
   TYPE_INT_ARGB);

Then, you obtain a graphics context to draw into the buffered image.

Graphics2D g2 = bufferedImage.createGraphics();

Any drawing operations on g2 now fill the buffered image with pixels. When you are done, then you can create your TexturePaint object:

g2.setPaint(new TexturePaint(bufferedImage, anchorRectangle));

The program in Example 7-4 lets the user choose between a solid color paint, a gradient paint, and a texture paint. Then, an ellipse is filled with the specified paint.

The texture paint uses an image that is read from a GIF file. As you will see later in this chapter, the ImageIO class makes it simple to read a graphics file into a buffered image, by calling

bufferedImage = ImageIO.read(new File("blue-ball.gif"));

NOTE

graphics/note.gif
 

The ImageIO class was added in SDK version 1.4. If you have an older version of the SDK, you need to use the following code instead:

Image image = Toolkit.getDefaultToolkit().getImage
   ("blue-ball.gif");
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(image, 0);
try { tracker.waitForID(0); }
catch (InterruptedException e) {}
bufferedImage = new BufferedImage(image.getWidth(null),
   image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = bufferedImage.createGraphics();
g2.drawImage(image, 0, 0, null);

To show the significance of the anchor rectangle, we specify the anchor to have twice the size of the image:

Rectangle2D anchor = new Rectangle2D.Double(0, 0,
   2 * bufferedImage.getWidth(),
   2 * bufferedImage.getHeight());
paint = new TexturePaint(bufferedImage, anchor);

As you can see when you select Texture Paint, the image is scaled to fit the anchor, and it is then replicated to fill the shape. Tiles that meet the boundary of the shape are clipped.

Example 7-4 PaintTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.awt.image.*;
  5. import java.io.*;
  6. import java.util.*;
  7. import javax.imageio.*;
  8. import javax.swing.*;
  9.
 10. /**
 11.    This program demonstrates the various paint modes.
 12. */
 13. public class PaintTest
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new PaintTestFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame contains radio buttons to choose the paint mode
 25.    and a panel that draws a circle in the selected paint mode.
 26. */
 27. class PaintTestFrame extends JFrame
 28. {
 29.    public PaintTestFrame()
 30.    {
 31.       setTitle("PaintTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       Container contentPane = getContentPane();
 35.       canvas = new PaintPanel();
 36.       contentPane.add(canvas, BorderLayout.CENTER);
 37.
 38.       JPanel buttonPanel = new JPanel();
 39.       ButtonGroup group = new ButtonGroup();
 40.
 41.       JRadioButton colorButton = new JRadioButton("Color", true);
 42.       buttonPanel.add(colorButton);
 43.       group.add(colorButton);
 44.       colorButton.addActionListener(new
 45.          ActionListener()
 46.          {
 47.             public void actionPerformed(ActionEvent event)
 48.             {
 49.                canvas.setColor();
 50.             }
 51.          });
 52.
 53.       JRadioButton gradientPaintButton
 54.          = new JRadioButton("Gradient Paint", false);
 55.       buttonPanel.add(gradientPaintButton);
 56.       group.add(gradientPaintButton);
 57.       gradientPaintButton.addActionListener(new
 58.          ActionListener()
 59.          {
 60.             public void actionPerformed(ActionEvent event)
 61.             {
 62.                canvas.setGradientPaint();
 63.             }
 64.          });
 65.
 66.       JRadioButton texturePaintButton
 67.          = new JRadioButton("Texture Paint", false);
 68.       buttonPanel.add(texturePaintButton);
 69.       group.add(texturePaintButton);
 70.       texturePaintButton.addActionListener(new
 71.          ActionListener()
 72.          {
 73.             public void actionPerformed(ActionEvent event)
 74.             {
 75.                canvas.setTexturePaint();
 76.             }
 77.          });
 78.
 79.       contentPane.add(buttonPanel, BorderLayout.NORTH);
 80.    }
 81.
 82.    private PaintPanel canvas;
 83.    private static final int WIDTH = 400;
 84.    private static final int HEIGHT = 400;
 85. }
 86.
 87. /**
 88.    This panel paints a circle in various paint modes.
 89. */
 90. class PaintPanel extends JPanel
 91. {
 92.    public PaintPanel()
 93.    {
 94.       try
 95.       {
 96.          bufferedImage = ImageIO.read(new File("blue-ball.gif"));
 97.       }
 98.       catch (IOException exception)
 99.       {
100.          exception.printStackTrace();
101.       }
102.       setColor();
103.    }
104.
105.    public void paintComponent(Graphics g)
106.    {
107.       super.paintComponent(g);
108.       Graphics2D g2 = (Graphics2D)g;
109.       g2.setPaint(paint);
110.       Ellipse2D circle
111.          = new Ellipse2D.Double(0, 0, getWidth(), getHeight());
112.       g2.fill(circle);
113.    }
114.
115.    /**
116.       Paints in a plain color.
117.    */
118.    public void setColor()
119.    {
120.       paint = Color.red; // Color implements Paint
121.       repaint();
122.    }
123.
124.    /**
125.       Sets the paint mode to gradient paint.
126.    */
127.    public void setGradientPaint()
128.    {
129.       paint = new GradientPaint(0, 0, Color.red,
130.          (float)getWidth(), (float)getHeight(), Color.blue);
131.       repaint();
132.    }
133.
134.    /**
135.       Sets the paint mode to texture paint.
136.    */
137.    public void setTexturePaint()
138.    {
139.       Rectangle2D anchor = new Rectangle2D.Double(0, 0,
140.          2 * bufferedImage.getWidth(),
141.          2 * bufferedImage.getHeight());
142.       paint = new TexturePaint(bufferedImage, anchor);
143.       repaint();
144.    }
145.
146.    private Paint paint;
147.    private BufferedImage bufferedImage;
148. }

java.awt.Graphics2D

graphics/api.gif
 

java.awt.GradientPaint

graphics/api.gif
 

java.awt.TexturePaint

graphics/api.gif
 

Coordinate Transformations

Suppose you need to draw an object such as an automobile. You know, from the manufacturer's specifications, the height, wheelbase, and total length. You could, of course, figure out all pixel positions, assuming some number of pixels per meter. However, there is an easier way. You can ask the graphics context to carry out the conversion for you.

g2.scale(pixelsPerMeter, pixelsPerMeter);
g2.draw(new Line2D.Double(coordinates in meters));
   // converts to pixels and draws scaled line

The scale method of the Graphics2D class sets the coordinate transformation of he graphics context to a scaling transformation. That transformation changes user coordinates (the units that the user specifies) to device coordinates (pixels). Figure 7-18 shows how the transformation works.

Figure 7-18. User and device coordinates

graphics/07fig18.gif

Coordinate transformations are very useful in practice. They allow you to work with convenient coordinate values. The graphics context takes care of the dirty work of transforming them to pixels.

There are four fundamental transformations:

Figure 7-19 shows how these four fundamental transformations act on a unit square.

Figure 7-19. The fundamental transformations

graphics/07fig19.gif

The scale, rotate, translate, and shear methods of the Graphics2D class set the coordinate transformation of the graphics context to one of these fundamental transformations.

You can compose the transformations. For example, you may want to rotate shapes and double their size. Then, you need to supply both a rotation and a scaling transformation.

g2.rotate(angle);
g2.scale(2, 2);
g2.draw(. . .);

In this case, it does not matter in which order you supply the transformations. However, with most transformations, order does matter. For example, if you want to rotate and shear, then it makes a difference which of the transformations you supply first. You need to figure out what your intention is. The graphics context will apply the transformations in the opposite order in which you supplied them. That is, the last transformation that you supply is applied first.

You can supply as many transformations as you like. For example, consider the following sequence of transformations:

g2.translate(x, y);
g2.rotate(a);
g2.translate(-x, -y);

The last transformation (which is applied first) moves the point (x, y) to the origin. The second transformation rotates with an angle a around the origin. The final transformation moves the origin back to (x, y). The overall effect is a rotation with center point (x, y)—see Figure 7-20. Because rotating about a point other than the origin is such a common operation, there is a shortcut:

Figure 7-20. Composing transformations

graphics/07fig20.gif
 

g2.rotate(a, x, y);

If you know some matrix theory, you are probably aware that all rotations, translations, scalings, shears, and their compositions can be expressed by matrix transformations of the form:

Such a transformation is called an affine transformation. In the Java 2D API, the AffineTransform class describes such a transformation. If you know the components of a particular transformation matrix, you can construct it directly as

AffineTransform t = new AffineTransform(a, b, c, d, e, f);

There are also factory methods getRotateInstance, getScaleInstance, getTranslateInstance, and getShearInstance that construct the matrices that represent these transformation types. For example, the call

t = AffineTransform.getScaleInstance(2.0F, 0.5F);

returns a transformation that corresponds to the matrix
 

graphics/07fig20a.gif
 

Finally, there are instance methods setToRotation, setToScale, setToTranslation, and setToShear that set a transformation object to a new type. Here is an example.

t.setToRotation(angle); // sets t to a rotation

You can set the coordinate transformation of the graphics context to an AffineTransform object.

g2.setTransform(t); // replaces current transformation

However, in practice, you don't want to call the setTransform operation since it replaces any existing clipping shape that the graphics context may have. For example, a graphics context for printing in landscape mode already contains a 90-degree rotation transformation. If you call setTransform, you obliterate that rotation. Instead, call the transform method.

g2.transform(t); // composes current transformation with t

It composes the existing transformation with the new AffineTransform object.

If you just want to apply a transformation temporarily, then you should first get the old transformation, then compose with your new transformation, and finally restore the old transformation when you are done.

AffineTransform oldTransform = g2.getTransform();
   // save old transform
g2.transform(t); // apply temporary transform
   // now draw on g2
g2.setTransform(oldTransform); // restore old transform

The program in Example 7-5 lets the user choose among the four fundamental transformations. The paintComponent method draws a square, then applies the selected transformation and redraws the square. However, for a good visual appearance, we want to have the square and its transform appear on the center of the display panel. For that reason, the paintComponent method first sets the coordinate transformation to a translation.

g2.translate(getWidth() / 2, getHeight() / 2);

This translation moves the origin to the center of the component.

Then, the paintComponent method draws a square that is centered around the origin.

square = new Rectangle2D.Double(-50, -50, 100, 100);
. . .
g2.setPaint(Color.gray);
g2.draw(square);

However, because the graphics context applies the translation to the shape, the square is actually drawn with its center lying at the center of the component.

Next, the transformation that the user selected is composed with the current transformation, and the square is drawn once again.

g2.transform(t);
g2.setPaint(Color.black);
g2.draw(square);

The original square is drawn in gray, and the transformed one in black (see Figure 7-21).

Figure 7-21. The TransformTest program

graphics/07fig21.gif

Example 7-5 TransformTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.util.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program displays the effects of various transformations.
  9. */
 10. public class TransformTest
 11. {
 12.    public static void main(String[] args)
 13.    {
 14.       JFrame frame = new TransformTestFrame();
 15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 16.       frame.show();
 17.    }
 18. }
 19.
 20. /**
 21.    This frame contains radio buttons to choose a transformations
 22.    and a panel to display the effect of the chosen
 23.    transformation.
 24. */
 25. class TransformTestFrame extends JFrame
 26. {
 27.    public TransformTestFrame()
 28.    {
 29.       setTitle("TransformTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       Container contentPane = getContentPane();
 33.       canvas = new TransformPanel();
 34.       contentPane.add(canvas, BorderLayout.CENTER);
 35.
 36.       JPanel buttonPanel = new JPanel();
 37.       ButtonGroup group = new ButtonGroup();
 38.
 39.       JRadioButton rotateButton
 40.          = new JRadioButton("Rotate", true);
 41.       buttonPanel.add(rotateButton);
 42.       group.add(rotateButton);
 43.       rotateButton.addActionListener(new
 44.          ActionListener()
 45.          {
 46.             public void actionPerformed(ActionEvent event)
 47.             {
 48.                canvas.setRotate();
 49.             }
 50.          });
 51.
 52.       JRadioButton translateButton
 53.          = new JRadioButton("Translate", false);
 54.       buttonPanel.add(translateButton);
 55.       group.add(translateButton);
 56.       translateButton.addActionListener(new
 57.          ActionListener()
 58.          {
 59.             public void actionPerformed(ActionEvent event)
 60.             {
 61.                canvas.setTranslate();
 62.             }
 63.          });
 64.
 65.       JRadioButton scaleButton
 66.          = new JRadioButton("Scale", false);
 67.       buttonPanel.add(scaleButton);
 68.       group.add(scaleButton);
 69.       scaleButton.addActionListener(new
 70.          ActionListener()
 71.          {
 72.             public void actionPerformed(ActionEvent event)
 73.             {
 74.                canvas.setScale();
 75.             }
 76.          });
 77.
 78.       JRadioButton shearButton
 79.          = new JRadioButton("Shear", false);
 80.       buttonPanel.add(shearButton);
 81.       group.add(shearButton);
 82.       shearButton.addActionListener(new
 83.          ActionListener()
 84.          {
 85.             public void actionPerformed(ActionEvent event)
 86.             {
 87.                canvas.setShear();
 88.             }
 89.          });
 90.
 91.       contentPane.add(buttonPanel, BorderLayout.NORTH);
 92.    }
 93.
 94.    private TransformPanel canvas;
 95.    private static final int WIDTH = 300;
 96.    private static final int HEIGHT = 300;
 97. }
 98.
 99. /**
100.    This panel displays a square and its transformed image
101.    under a transformation.
102. */
103. class TransformPanel extends JPanel
104. {
105.    public TransformPanel()
106.    {
107.       square = new Rectangle2D.Double(-50, -50, 100, 100);
108.       t = new AffineTransform();
109.       setRotate();
110.    }
111.
112.    public void paintComponent(Graphics g)
113.    {
114.       super.paintComponent(g);
115.       Graphics2D g2 = (Graphics2D)g;
116.       g2.translate(getWidth() / 2, getHeight() / 2);
117.       g2.setPaint(Color.gray);
118.       g2.draw(square);
119.       g2.transform(t);
120.          /* we don't use setTransform because we want
121.             to compose with the current translation
122.          */
123.       g2.setPaint(Color.black);
124.       g2.draw(square);
125.    }
126.
127.    /**
128.       Set the transformation to a rotation.
129.    */
130.    public void setRotate()
131.    {
132.       t.setToRotation(Math.toRadians(30));
133.       repaint();
134.    }
135.
136.    /**
137.       Set the transformation to a translation.
138.    */
139.    public void setTranslate()
140.    {
141.       t.setToTranslation(20, 15);
142.       repaint();
143.    }
144.
145.    /**
146.       Set the transformation to a scale transformation.
147.    */
148.    public void setScale()
149.    {
150.       t.setToScale(2.0, 1.5);
151.       repaint();
152.    }
153.
154.    /**
155.       Set the transformation to a shear transformation.
156.    */
157.    public void setShear()
158.    {
159.       t.setToShear(-0.2, 0);
160.       repaint();
161.    }
162.
163.    private Rectangle2D square;
164.    private AffineTransform t;
165. }

java.awt.geom.AffineTransform

graphics/api.gif
 

java.awt.Graphics2D

graphics/api.gif
 

Clipping

By setting a clipping shape in the graphics context, you constrain all drawing operations the interior of that clipping shape.

g2.setClip(clipShape); // but see below
g2.draw(shape);
   // draws only the part that falls inside the clipping shape

However, in practice, you don't want to call the setClip operation since it replaces any existing clipping shape that the graphics context may have. For example, as you will see later in this chapter, a graphics context for printing comes with a clip rectangle that ensures that you don't draw on the margins. Instead, call the clip method.

g2.clip(clipShape); // better

The clip method intersects the existing clipping shape with the new one that you supply.

If you just want to apply a clipping area temporarily, then you should first get the old clip, then add your new clip, and finally restore the old clip when you are done:

Shape oldClip = g2.getClip(); // save old clip
g2.clip(clipShape); // apply temporary clip
// now draw on g2
g2.setClip(oldClip); // restore old clip

In Example 7-6, we show off the clipping capability with a rather dramatic drawing of a line pattern that is clipped by a complex shape, namely, the outline of a set of characters (see Figure 7-22).

Figure 7-22. The ClipTest program

graphics/07fig22.gif

To obtain character outlines, you need a font render context. Use the getFontRenderContext method of the Graphics2D class.

FontRenderContext context = g2.getFontRenderContext();

Next, using

create a TextLayout object:

TextLayout layout = new TextLayout("Hello", font, context);

This text layout object describes the layout of a sequence of characters, as rendered by a particular font render context. The layout depends on the font render context—the same characters will appear differently on a screen or a printer.

More importantly for our current application, the getOutline method returns a Shape object that describes the shape of the outline of the characters in the text layout. The outline shape starts at the origin (0, 0), which is not suitable for most drawing operations. Therefore, you need to supply an affine transform to the getOutline operation that specifies where you would like the outline to appear. We simply supply a translation that moves the base point to the point (0, 100).

AffineTransform transform
   = AffineTransform.getTranslateInstance(0, 100);
Shape outline = layout.getOutline(transform);

Then, we append the outline to the clipping shape.

GeneralPath clipShape = new GeneralPath();
clipShape.append(outline, false);

Finally, we set the clipping shape and draw a set of lines. The lines appear only inside the character boundaries.

g2.setClip(clipShape);
Point2D p = new Point2D.Double(0, 0);
for (int i = 0; i < NLINES; i++)
{
   double x = . . .;
   double y = . . .;
   Point2D q = new Point2D.Double(x, y);
   g2.draw(new Line2D.Double(p, q)); // lines are clipped
}

Here is the complete program.

Example 7-6 ClipTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.awt.font.*;
 4. import java.awt.geom.*;
 5. import java.util.*;
 6. import javax.swing.*;
 7.
 8. /**
 9.    This program demonstrates the use of a clip shape.
10. */
11. public class ClipTest
12. {
13.    public static void main(String[] args)
14.    {
15.       JFrame frame = new ClipTestFrame();
16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17.       frame.show();
18.    }
19. }
20.
21. /**
22.    This frame contains radio buttons to turn a clip off
23.    and on, and a panel to draw a set of lines with or without
24.    clipping.
25. */
26. class ClipTestFrame extends JFrame
27. {
28.    public ClipTestFrame()
29.    {
30.       setTitle("ClipTest");
31.       setSize(WIDTH, HEIGHT);
32.
33.       Container contentPane = getContentPane();
34.
35.       final JCheckBox checkBox = new JCheckBox("Clip");
36.       checkBox.addActionListener(new
37.          ActionListener()
38.          {
39.             public void actionPerformed(ActionEvent event)
40.             {
41.                panel.repaint();
42.             }
43.          });
44.       contentPane.add(checkBox, BorderLayout.NORTH);
45.
46.       panel = new
47.          JPanel()
48.          {
49.             public void paintComponent(Graphics g)
50.             {
51.                super.paintComponent(g);
52.                Graphics2D g2 = (Graphics2D)g;
53.
54.                if (clipShape == null)
55.                   clipShape = makeClipShape(g2);
56.
57.                g2.draw(clipShape);
58.
59.                if (checkBox.isSelected())
60.                   g2.clip(clipShape);
61.
62.                // draw line pattern
63.                final int NLINES =50;
64.                Point2D p = new Point2D.Double(0, 0);
65.                for (int i = 0; i < NLINES; i++)
66.                {
67.                   double x = (2 * getWidth() * i) / NLINES;
68.                  double y = (2 * getHeight() * (NLINES - 1 - i))
69.                      / NLINES;
70.                   Point2D q = new Point2D.Double(x, y);
71.                   g2.draw(new Line2D.Double(p, q));
72.                }
73.             }
74.          };
75.       contentPane.add(panel, BorderLayout.CENTER);
76.    }
77.
78.    /**
79.       Makes the clip shape.
80.       @param g2 the graphics context
81.       @return the clip shape
82.    */
83.    Shape makeClipShape(Graphics2D g2)
84.    {
85.       FontRenderContext context = g2.getFontRenderContext();
86.       Font f = new Font("Serif", Font.PLAIN, 100);
87.       GeneralPath clipShape = new GeneralPath();
88.
89.       TextLayout layout = new TextLayout("Hello", f, context);
90.       AffineTransform transform
91.          = AffineTransform.getTranslateInstance(0, 100);
92.       Shape outline = layout.getOutline(transform);
93.       clipShape.append(outline, false);
94.
95.       layout = new TextLayout("World", f, context);
96.       transform
97.          = AffineTransform.getTranslateInstance(0, 200);
98.       outline = layout.getOutline(transform);
99.       clipShape.append(outline, false);
100.      return clipShape;
101.   }
102.
103.   private JPanel panel;
104.   private Shape clipShape;
105.   private static final int WIDTH = 300;
106.   private static final int HEIGHT = 300;
107. }

java.awt.Graphics

graphics/api.gif
 

java.awt.Graphics2D

graphics/api.gif
 

java.awt.font.TextLayout

graphics/api.gif
 

Transparency and Composition

In the standard RGB color model, every color is described by its red, green, and blue components. However, it is also convenient to be able to describe areas of an image that are transparent or partially transparent. When you superimpose an image onto an existing drawing, the transparent pixels do not obscure the pixels under them at all, whereas partially transparent pixels are mixed with the pixels under them. Figure 7-23 shows the effect of overlaying a partially transparent rectangle on an image. You can still see the details of the image shine through from under the rectangle.

Figure 7-23. Overlaying a partially transparent rectangle on an image

graphics/07fig23.jpg

In the Java 2D API, transparency is described by an alpha channel. Each pixel has, in addition to its red, green, and blue color components, an alpha value between 0 (fully transparent) and 1 (fully opaque). For example, the rectangle in Figure 7-23 was filled with a pale yellow color with 50% transparency:

new Color(0.7F, 0.7F, 0.0F, 0.5F);

Now let us look at what happens if you superimpose two shapes. You need to blend or compose the colors and alpha values of the source and destination pixels. Porter and Duff, two researchers in the field of computer graphics, have formulated twelve possible composition rules for this blending process. The Java 2D API implements eight of these rules. Before we go any further, we'd like to point out that only two of these rules have practical significance. If you find the rules arcane or confusing, just use the SRC_OVER rule. It is the default rule for a Graphics2D object, and it gives the most intuitive results.

Here is the theory behind the rules. Suppose you have a source pixel with alpha value aS.In the image, there is already a destination pixel with alpha value aD. You want to compose the two. The diagram in Figure 7-24 shows how to design a composition rule.

Figure 7-24. Designing a Composition Rule

graphics/07fig24.gif

Porter and Duff consider the alpha value as the probability that the pixel color should be used. From the perspective of the source, there is a probability aS that it wants to use the source color and a probability of 1 -aS that it doesn't care. The same holds for the destination. When composing the colors, let us assume that the probabilities are independent. Then there are four cases, as shown in Figure 7-24. If the source wants to use the source color, and the destination doesn't care, then it seems reasonable to let the source have its way. That's why the upper-right corner of the diagram is labeled "S." The probability for that event is aS·(1 - aD). Similarly, the lower-left corner is labeled "D." What should one do if both destination and source would like to select their color? That's where the Porter-Duff rules come in. If we decide that the source is more important, then we label the lower-right corner with an "S" as well. That rule is called SRC_OVER. In that rule, you combine the source colors with a weight of aS and the destination colors with a weight of (1 - aS)·aD.

The visual effect is a blending of the source and destination, with preference given to the source. In particular, if aS is 1, then the destination color is not taken into account at all. If aS is zero, then the source pixel is completely transparent and the destination color is unchanged.

There are other rules, depending on what letters you put in the boxes of the probability diagram. Table 7-1 and Figure 7-25 show all rules that are supported by the Java 2D API. The images in the figure show the results of the rules when a rectangular source region with an alpha of 0.75 is combined with an elliptical destination region with an alpha of 1.0.

Figure 7-25. Porter-Duff Composition Rules

graphics/07fig25.gif
 

Table 7-1. The Porter-Duff Composition Rules
CLEAR Source clears destination.
SRC Source overwrites destination and empty pixels.
DST Source does not affect destination.
SRC_OVER Source blends with destination and overwrites empty pixels.
DST_OVER Source does not affect destination and overwrites empty pixels.
SRC_IN Source overwrites destination.
SRC_OUT Source clears destination and overwrites empty pixels.
DST_IN Source alpha modifies destination.
DST_OUT Source alpha complement modifies destination.
SRC_ATOP Source blends with destination.
DST_ATOP Source alpha modifies destination. Source overwrites empty pixels.
XOR Source alpha complement modifies destination. Source overwrites empty pixels.

As you can see, most of the rules aren't very useful. Consider, as an extreme case, the DST_IN rule. It doesn't take the source color into account at all, but it uses the alpha of the source to affect the destination. The SRC rule is potentially useful—it forces the source color to be used, turning off blending with the destination.

The DST, SRC_ATOP, DST_ATOP, and XOR rules have been added in SDK 1.4.

For more information on the Porter-Duff rules, see, for example, Foley, van Dam, Feiner, et al., Section 17.6.1.

You use the setComposite method of the Graphics2D class to install an object of a class that implements the Composite interface. The Java 2D API supplies one such class, AlphaComposite, that implements the eight Porter-Duff rules in Figure 7-25.

The factory method getInstance of the AlphaComposite class yields an AlphaComposite object. You need to supply the rule and the alpha value to be used for source pixels. For example, consider the following code.

int rule = AlphaComposite.SRC_OVER;
float alpha = 0.5;
g2.setComposite(AlphaComposite.getInstance(rule, alpha));
g2.setPaint(Color.blue);
g2.fill(rectangle);

Then, the rectangle is painted with blue color and an alpha value of 0.5. Because the composition rule is SRC_OVER, it is transparently overlaid on the existing image.

The program in Example 7-7 lets you explore these composition rules. Pick a rule from the combo box and use the slider to set the alpha value of the AlphaComposite object.

Furthermore, the program displays a verbal description of each rule. Note that the descriptions are computed from the composition rule diagrams. For example, a "DS" in the second row stands for "blends with destination."

The program has one important twist. There is no guarantee that the graphics context that corresponds to the screen has an alpha channel. (In fact, it generally does not.) When pixels are deposited to a destination without an alpha channel, then the pixel colors are multiplied with the alpha value and the alpha value is discarded. Since several of the Porter-Duff rules use the alpha values of the destination, a destination alpha channel is important. For that reason, we use a buffered image with the ARGB color model to compose the shapes. After the images have been composed, we draw the resulting image to the screen.

BufferedImage image = new BufferedImage(getWidth(),
   getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D gImage = image.createGraphics();
// now draw to gImage
g2.drawImage(image, null, 0, 0);

Here is the complete code for the program. Figure 7-26 shows the screen display. As you run the program, move the alpha slider from left to right to see the effect on the composed shapes. In particular, note that the only difference between the DST_IN and DST_OUT rules is how the destination (!) color changes when you change the source alpha.

Figure 7-26. The CompositeTest program

graphics/07fig26.gif

Example 7-7 CompositeTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.image.*;
  4. import java.awt.geom.*;
  5. import java.util.*;
  6. import javax.swing.*;
  7. import javax.swing.event.*;
  8.
  9. /**
 10.    This program demonstrates the Porter-Duff composition rules.
 11. */
 12. public class CompositeTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new CompositeTestFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame contains a combo box to choose a composition
 24.    rule, a slider to change the source alpha channel,
 25.    and a panel that shows the composition.
 26. */
 27. class CompositeTestFrame extends JFrame
 28. {
 29.    public CompositeTestFrame()
 30.    {
 31.       setTitle("CompositeTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       Container contentPane = getContentPane();
 35.       canvas = new CompositePanel();
 36.       contentPane.add(canvas, BorderLayout.CENTER);
 37.
 38.       ruleCombo = new JComboBox(new
 39.          Object[]
 40.          {
 41.             new Rule("CLEAR", "  ", "  "),
 42.             new Rule("SRC", " S", " S"),
 43.             new Rule("DST", "  ", "DD"),
 44.             new Rule("SRC_OVER", " S", "DS"),
 45.             new Rule("DST_OVER", " S", "DD"),
 46.             new Rule("SRC_IN", "  ", " S"),
 47.             new Rule("SRC_OUT", " S", "  "),
 48.             new Rule("DST_IN", "  ", " D"),
 49.             new Rule("DST_OUT", "  ", "D "),
 50.             new Rule("SRC_ATOP", "  ", "DS"),
 51.             new Rule("DST_ATOP", " S", " D"),
 52.             new Rule("XOR", " S", "D "),
 53.          });
 54.       ruleCombo.addActionListener(new
 55.          ActionListener()
 56.          {
 57.             public void actionPerformed(ActionEvent event)
 58.             {
 59.                Rule r = (Rule)ruleCombo.getSelectedItem();
 60.                canvas.setRule(r.getValue());
 61.                explanation.setText(r.getExplanation());
 62.             }
 63.           });
 64.
 65.       alphaSlider = new JSlider(0, 100, 75);
 66.       alphaSlider.addChangeListener(new
 67.          ChangeListener()
 68.          {
 69.             public void stateChanged(ChangeEvent event)
 70.             {
 71.                canvas.setAlpha(alphaSlider.getValue());
 72.             }
 73.          });
 74.       JPanel panel = new JPanel();
 75.       panel.add(ruleCombo);
 76.       panel.add(new JLabel("Alpha"));
 77.       panel.add(alphaSlider);
 78.       contentPane.add(panel, BorderLayout.NORTH);
 79.
 80.       explanation = new JTextField();
 81.       contentPane.add(explanation, BorderLayout.SOUTH);
 82.
 83.       canvas.setAlpha(alphaSlider.getValue());
 84.       Rule r = (Rule)ruleCombo.getSelectedItem();
 85.       canvas.setRule(r.getValue());
 86.       explanation.setText(r.getExplanation());
 87.    }
 88.
 89.    private CompositePanel canvas;
 90.    private JComboBox ruleCombo;
 91.    private JSlider alphaSlider;
 92.    private JTextField explanation;
 93.    private static final int WIDTH = 400;
 94.    private static final int HEIGHT = 400;
 95. }
 96.
 97. /**
 98.    This class describes a Porter-Duff rule.
 99. */
100. class Rule
101. {
102.    /**
103.       Constructs a Porter-Duff rule
104.       @param n the rule name
105.       @param pd1 the first row of the Porter-Duff square
106.       @param pd2 the second row of the Porter-Duff square
107.    */
108.    public Rule(String n, String pd1, String pd2)
109.    {
110.       name = n;
111.       porterDuff1 = pd1;
112.       porterDuff2 = pd2;
113.    }
114.
115.    /**
116.       Gets an explanation of the behavior of this rule.
117.       @return the explanation
118.    */
119.    public String getExplanation()
120.    {
121.       StringBuffer r = new StringBuffer("Source ");
122.       if (porterDuff2.equals("  "))
123.          r.append("clears");
124.       if (porterDuff2.equals(" S"))
125.          r.append("overwrites");
126.       if (porterDuff2.equals("DS"))
127.          r.append("blends with");
128.       if (porterDuff2.equals(" D"))
129.          r.append("alpha modifies");
130.       if (porterDuff2.equals("D "))
131.          r.append("alpha complement modifies");
132.       if (porterDuff2.equals("DD"))
133.           r.append("does not affect");
134.       r.append(" destination");
135.       if (porterDuff1.equals(" S"))
136.          r.append(" and overwrites empty pixels");
137.       r.append(".");
138.       return r.toString();
139.    }
140.
141.    public String toString()
142.    {
143.       return name;
144.    }
145.
146.    /**
147.       Gets the value of this rule in the AlphaComposite class
148.       @return the AlphaComposite constant value, or -1 if
149.       there is no matching constant.
150.    */
151.    public int getValue()
152.    {
153.       try
154.       {
155.          Integer i = (Integer)
156.             AlphaComposite.class.getField(name).get(null);
157.          return i.intValue();
158.       }
159.       catch (Exception ex)
160.       {
161.          return -1;
162.       }
163.    }
164.
165.    private String name;
166.    private String porterDuff1;
167.    private String porterDuff2;
168. }
169.
170. /**
171.    This panel draws two shapes, composed with a
172.    composition rule.
173. */
174. class CompositePanel extends JPanel
175. {
176.    public CompositePanel()
177.    {
178.       shape1 = new Ellipse2D.Double(100, 100, 150, 100);
179.       shape2 = new Rectangle2D.Double(150, 150, 150, 100);
180.    }
181.
182.    public void paintComponent(Graphics g)
183.    {
184.       super.paintComponent(g);
185.       Graphics2D g2 = (Graphics2D)g;
186.
187.       BufferedImage image = new BufferedImage(getWidth(),
188.          getHeight(), BufferedImage.TYPE_INT_ARGB);
189.       Graphics2D gImage = image.createGraphics();
190.       gImage.setPaint(Color.red);
191.       gImage.fill(shape1);
192.       AlphaComposite composite
193.          = AlphaComposite.getInstance(rule, alpha);
194.       gImage.setComposite(composite);
195.       gImage.setPaint(Color.blue);
196.       gImage.fill(shape2);
197.       g2.drawImage(image, null, 0, 0);
198.    }
199.
200.    /**
201.       Sets the composition rule.
202.       @param r the rule (as an AlphaComposite constant)
203.    */
204.    public void setRule(int r)
205.    {
206.       rule = r;
207.       repaint();
208.    }
209.
210.    /**
211.       Sets the alpha of the source
212.       @param a the alpha value between 0 and 100
213.    */
214.    public void setAlpha(int a)
215.    {
216.       alpha = (float)a / 100.0F;
217.       repaint();
218.    }
219.
220.    private int rule;
221.    private Shape shape1;
222.    private Shape shape2;
223.    private float alpha;
224. }

java.awt.Graphics2D

graphics/api.gif
 

java.awt.AlphaComposite

graphics/api.gif
 

Rendering Hints

In the preceding sections you have seen that the rendering process is quite complex. While the Java 2D API is surprisingly fast in most cases, there are cases when you would like to have control over trade-offs between speed and quality. You achieve this by setting rendering hints. The setRenderingHint method of the Graphics2D class lets you set a single hint. The hint keys and values are declared in the RenderingHints class. Table 7-2 summarizes the choices.

The most useful of these settings involves antialiasing. This is a technique to remove the "jaggies" from slanted lines and curves. As you can see in Figure 7-27, a slanted line must be drawn as a "staircase" of pixels. Especially on low-resolution screens, this can look ugly. But if, rather than drawing each pixel completely on or off, you color in the pixels that are partially covered, with the color value proportional to the area of the pixel that the line covers, then the result looks much smoother. This technique is called antialiasing. Of course, antialiasing takes a bit longer because it takes time to compute all those color values.

Figure 7-27. Antialiasing

graphics/07fig27.gif
 

Table 7-2. Rendering Hints
Key Values Explanation
KEY_ANTIALIASING VALUE_ANTIALIAS_ON Turn antialiasing for shapes on or off.
VALUE_ANTIALIAS_OFF
VALUE_ANTIALIAS_DEFAULT
KEY_RENDERING VALUE_RENDER_QUALITY When available, select rendering algorithms for greater quality or speed.
VALUE_RENDER_SPEED
VALUE_RENDER_DEFAULT
KEY_DITHERING VALUE_DITHER_ENABLE Turn dithering for colors on or off. Dithering approximates color values by drawing groups of pixels of similar colors.
VALUE_DITHER_DISABLE
VALUE_DITHER_DEFAULT
KEY_TEXT_ANTIALIASING VALUE_TEXT_ANTIALIAS_ON Turn antialiasing for fonts on or off.
VALUE_TEXT_ANTIALIAS_OFF
VALUE_TEXT_ANTIALIAS_DEFAULT
KEY_FRACTIONAL_METRICS VALUE_FRACTIONALMETRICS_ON Turn the computation of fractional character dimensions on or off. Fractional character dimensions lead to better placement of characters.
VALUE_FRACTIONALMETRICS_OFF
VALUE_FRACTIONALMETRICS_DEFAULT
KEY_ALPHA_INTERPOLATION VALUE_ALPHA_INTERPOLATION_QUALITY Turn precise computation of alpha composites on or off.
VALUE_ALPHA_INTERPOLATION_SPEED
VALUE_ALPHA_INTERPOLATION_DEFAULT
KEY_COLOR_RENDERING VALUE_COLOR_RENDER_QUALITY Select quality or speed for color rendering.
VALUE_COLOR_RENDER_SPEED
VALUE_COLOR_RENDER_DEFAULT
KEY_INTERPOLATION VALUE_INTERPOLATION_NEAREST_NEIGHBOR Select a rule for interpolating pixels when scaling images.
VALUE_INTERPOLATION_BILINEAR
VALUE_INTERPOLATION_BICUBIC
KEY_STROKE_CONTROL VALUE_STROKE_NORMALIZE Select a rule for combining strokes.
VALUE_STROKE_PURE
VALUE_STROKE_DEFAULT

For example, here is how you can request the use of antialiasing.

g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
  RenderingHints.VALUE_ANTIALIAS_ON);

It also makes sense to use antialiasing for fonts.

g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

The other rendering hints are not as commonly used.

You can also put a bunch of key/value hint pairs into a map and set them all at once by calling the setRenderingHints method. Any collection class implementing the map interface will do, but you may as well use the RenderingHints class itself. It implements the Map interface and supplies a default map implementation if you pass null to the constructor. For example,

RenderingHints hints = new RenderingHints(null);
hints.put(RenderingHints.KEY_ANTIALIASING,
   RenderingHints.VALUE_ANTIALIAS_ON);
hints.put(RenderingHints.KEY_TEXT_ANTIALIASING,
   RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setRenderingHints(hints);

That is the technique that we use in Example 7-8. The program draws an image that we thought might benefit from some of the hints. You can turn various rendering hints on or off. Not all platforms support all the hints, so you should not expect every one of the settings to have an effect. On Windows 98, antialiasing smooths out the ellipse, and text antialiasing improves the look of the italic font. The other hints seemed to have no effect, but they might with other platforms or with more complex images.

Figure 7-28 shows a screen capture of the program.

Figure 7-28. The RenderingHints program

graphics/07fig28.jpg
 

Example 7-8 RenderQualityTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.io.*;
  5. import java.util.*;
  6. import javax.imageio.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    This program demonstrates the effect of the various
 11.    rendering hints.
 12. */
 13. public class RenderQualityTest
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new RenderQualityTestFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame contains buttons to set rendering hints
 25.    and an image that is drawn with the selected hints.
 26. */
 27. class RenderQualityTestFrame extends JFrame
 28. {
 29.    public RenderQualityTestFrame()
 30.    {
 31.       setTitle("RenderQualityTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       buttonBox = new JPanel();
 35.       buttonBox.setLayout(new GridLayout(9, 3));
 36.       hints = new RenderingHints(null);
 37.
 38.       makeButtons("KEY_ANTIALIASING",
 39.          "VALUE_ANTIALIAS_ON",
 40.          "VALUE_ANTIALIAS_OFF");
 41.       makeButtons("KEY_RENDERING",
 42.          "VALUE_RENDER_QUALITY",
 43.          "VALUE_RENDER_SPEED");
 44.       makeButtons("KEY_DITHERING",
 45.          "VALUE_DITHER_ENABLE",
 46.          "VALUE_DITHER_DISABLE");
 47.       makeButtons("KEY_TEXT_ANTIALIASING",
 48.          "VALUE_TEXT_ANTIALIAS_ON",
 49.          "VALUE_TEXT_ANTIALIAS_OFF");
 50.       makeButtons("KEY_FRACTIONALMETRICS",
 51.          "VALUE_FRACTIONALMETRICS_ON",
 52.          "VALUE_FRACTIONALMETRICS_OFF");
 53.        makeButtons("KEY_ALPHA_INTERPOLATION",
 54.          "VALUE_ALPHA_INTERPOLATION_QUALITY",
 55.          "VALUE_ALPHA_INTERPOLATION_SPEED");
 56.       makeButtons("KEY_COLOR_RENDERING",
 57.          "VALUE_COLOR_RENDER_QUALITY",
 58.          "VALUE_COLOR_RENDER_SPEED");
 59.       makeButtons("KEY_INTERPOLATION",
 60.          "VALUE_INTERPOLATION_NEAREST NEIGHBOR",
 61.          "VALUE_INTERPOLATION_BILINEAR");
 62.       makeButtons("KEY_STROKE_CONTROL",
 63.          "VALUE_STROKE_NORMALIZE",
 64.          "VALUE_STROKE_PURE");
 65.
 66.       Container contentPane = getContentPane();
 67.       canvas = new RenderQualityPanel();
 68.       contentPane.add(canvas, BorderLayout.CENTER);
 69.       contentPane.add(buttonBox, BorderLayout.NORTH);
 70.    }
 71.
 72.    /**
 73.       Makes a set of buttons for a rendering hint key and values
 74.       @param key the key name
 75.       @param value1 the name of the first value for the key
 76.       @param value2 the name of the second value for the key
 77.    */
 78.    void makeButtons(String key, String value1, String value2)
 79.    {
 80.       try
 81.       {
 82.          final RenderingHints.Key k = (RenderingHints.Key)
 83.             RenderingHints.class.getField(key).get(null);
 84.          final Object v1
 85.             = RenderingHints.class.getField(value1).get(null);
 86.          final Object v2
 87.             = RenderingHints.class.getField(value2).get(null);
 88.          JLabel label = new JLabel(key);
 89.          buttonBox.add(label);
 90.          ButtonGroup group = new ButtonGroup();
 91.          JRadioButton b1 = new JRadioButton(value1, true);
 92.          buttonBox.add(b1);
 93.          group.add(b1);
 94.          b1.addActionListener(new
 95.             ActionListener()
 96.             {
 97.                public void actionPerformed(ActionEvent event)
 98.                {
 99.                   hints.put(k, v1);
100.                   canvas.setRenderingHints(hints);
101.                }
102.          });
103.          JRadioButton b2 = new JRadioButton(value2, false);
104.          buttonBox.add(b2);
105.          group.add(b2);
106.          b2.addActionListener(new
107.             ActionListener()
108.             {
109.                public void actionPerformed(ActionEvent event)
110.                {
111.                   hints.put(k, v2);
112.                   canvas.setRenderingHints(hints);
113.                }
114.          });
115.          hints.put(k, v1);
116.       }
117.       catch (Exception ex)
118.       {
119.       }
120.    }
121.
122.    private RenderQualityPanel canvas;
123.    private JPanel buttonBox;
124.    private RenderingHints hints;
125.    private static final int WIDTH = 600;
126.    private static final int HEIGHT = 500;
127. }
128.
129. /**
130.    This panel produces a drawing that hopefully shows some
131.    of the difference caused by rendering hints.
132. */
133. class RenderQualityPanel extends JPanel
134. {
135.    public RenderQualityPanel()
136.    {
137.       color1 = new Color(0. 7F, 0. 7F, 0. 0F, 0. 5F);
138.       color2 = new Color(0. 0F, 0. 3F, 0. 3F, 0. 5F);
139.       try
140.       {
141.          image = ImageIO.read(new File("clouds.jpg"));
142.       }
143.       catch (IOException exception)
144.       {
145.          exception.printStackTrace();
146.       }
147.    }
148.
149.    public void paintComponent(Graphics g)
150.    {
151.       super.paintComponent(g);
152.       Graphics2D g2 = (Graphics2D)g;
153.       g2. setRenderingHints(hints);
154.
155.       g2. drawImage(image, 0, 0, null);
156.       g2. draw(new Ellipse2D.Double(0, 0,
157.           image.getWidth(null), image.getHeight(null)));
158.       g2. setFont(new Font("Serif", Font.ITALIC, 40));
159.       g2. drawString("Hello", 75, 75);
160.       g2. setPaint(color1);
161.       g2. translate(0,-80);
162.       g2. fill(new Rectangle2D.Double(100, 100, 200, 100));
163.       g2. setPaint(color2);
164.       g2. fill(new Rectangle2D.Double(120, 120, 200, 100));
165.    }
166.
167.    /**
168.       Sets the hints and repaints.
169.       @param h the rendering hints
170.    */
171.    public void setRenderingHints(RenderingHints h)
172.    {
173.       hints = h;
174.       repaint();
175.    }
176.
177.    private RenderingHints hints = new RenderingHints(null);
178.    private Color color1;
179.    private Color color2;
180.    private Image image;
181. }

java.awt.Graphics2D

graphics/api.gif
 

java.awt.RenderingHints

graphics/api.gif
 

Reading and Writing Images

Prior to version 1.4, the Java SDK had very limited capabilities for reading and writing image files. It was possible to read GIF and JPEG images, but there was no official support for writing images at all.

This situation is now much improved. SDK 1.4 introduces the javax.imageio package that contains "out of the box" support for reading and writing several common file formats, as well as a framework that enables third parties to add readers and writers for other formats. Specifically, the SDK contains readers for the GIF, JPEG, and PNG formats and writers for JPEG and PNG. (We suspect that writing GIF files is not supported due to patent issues.)

NOTE

graphics/note.gif
 

If you use an older version of the SDK, you need to look elsewhere to write GIF and JPEG files. You can find a GIF encoder at www.acme.com/java. There is a package, com.sun.image.codec.jpeg, that is part of the SDK from Sun Microsystems and that supports saving images in JPEG format. You can find more information about this package at http://java.sun.com/products/jdk/1.2/docs/guide/2d/api-jpeg/overview-summary.html.

The basics of the library are extremely straightforward. To load an image, use the static read method of the ImageIO class:

File f = . . .;
BufferedImage image = ImageIO.read(f);

The ImageIO class picks an appropriate reader, based on the file type. It may consult the file extension and the "magic number" at the beginning of the file for that purpose. If no suitable reader can be found or the reader can't decode the file contents, then the read method returns null.

Writing an image to a file is just as simple:

File f = . . .;
String format = . . .;
ImageIO.write(image, format, f);

Here the format string is a string identifying the image format, such as "JPEG" or "PNG". The ImageIO class picks an appropriate writer and saves the file.

Obtaining Readers and Writers for Image File Types

For more advanced image reading and writing operations that go beyond the static read and write methods of the ImageIO class, you first need to get the appropriate ImageReader and ImageWriter objects. The ImageIO class enumerates readers and writers that match one of the following:

NOTE

graphics/note.gif
 

MIME is the Multipurpose Internet Mail Extensions standard. The MIME standard defines common data formats such as "image/jpeg" and "application/pdf". For an HTML version of the RFC (Request for Comments) that defines the MIME format, see http://www.oac.uci.edu/indiv/ehood/MIME.

For example, you can obtain a reader that reads JPEG files as follows:

ImageReader reader = null;
Iterator iter = ImageIO.getImageReadersByFormatName("JPEG");
if (iter.hasNext) reader = (ImageReader)iter.next();

The getImageReadersBySuffix and getImageReadersByMIMEType method enumerate readers that match a file extension or MIME type.

It is possible that the ImageIO class can locate multiple readers that can all read a particular image type. In that case, you have to pick one of them, but it isn't clear how you can decide which one is the best. To find out more information about a reader, obtain its service provider interface:

ImageReaderSpi spi = reader.getOriginatingProvider();

Then you can get the vendor name and version number:

String vendor = spi.getVendor();
String version = spi.getVersion();

Perhaps that information can help you to decide among the choices, or you may just present a list of readers to your program users and make them choose. However, for now, we will assume that the first enumerated reader is at least adequate.

In the sample program at the end of this section, we have a couple of problems that the API doesn't address well. First, we want to find all file suffixes of all available readers, so that we can use them in a file filter. The IOImage class is willing to tell us the names of all reader formats and the names of all supported MIME types. But we can't enumerate all supported file suffixes, nor can we get all readers. So, we first enumerate all format names, then we get all readers for a given format name. An ImageReader won't reveal the supported file suffixes, but the associated service provider interface object does. With a couple of nested loops and the handy addAll method of the Set interface, we manage to collect all file suffixes. You can find the full code in the getReaderSuffixes method in Example 7-9.

For saving files, we have a similar problem. We'd like to present the user a menu of all supported image types. Unfortunately, the getWriterFormatNames of the IOImage class returns a rather curious list with redundant names, such as

JPG
jpeg
jpg
PNG
JPEG
png

That's not something one would want to present in a menu. It would be nice if there was some notion of a "preferred" format name. To pare down the list, we pick the first format name and look up the first writer associated with it. Then we ask it what its format names are, in the hope that it will list the most popular one first. Indeed, for the JPEG writer, this works fine: It lists "JPEG" before the other options. The PNG writer, on the other hand, lists "png" in lowercase before "PNG". Hopefully, that will be addressed at some time in the future. (We don't want to force the format name into uppercase—that wouldn't work for a format such as "PostScript".)

Once we pick a writer, we add the first format name to the format name set and remove all of its format names from the original set. We keep going until all format names are handled. The details are in the getWriterFormats method of Example 7-9. Note that this method would break down if someone would provide a single writer that can write multiple image formats.

As a practical matter, most programmers won't be bothered by these issues. If you have a fixed number of file formats that your application supports, then you can simply find the appropriate readers, writers, and file suffixes for them.

Reading and Writing Files with Multiple Images

Some files, in particular, animated GIF files, contain multiple images. The read method of the ImageIO class reads a single image. To read multiple images, turn the input source (for example, an input stream or file) into an ImageInputStream.

InputStream in = . . .;
ImageInputStream imageIn = ImageIO.createImageInputStream(in);

Then attach the image input stream to the reader:

reader.setInput(imageIn, true);

The second parameter indicates that the input is in "seek forward only" mode. Otherwise, random access is used, either by buffering stream input as it is read, or by using random file access. Random access is required for certain operations. For example, to find out the number of images in a GIF file, you need to read the entire file. If you then want to fetch an image, the input must be read again.

This consideration is only important if you read from a stream, and if the input contains multiple images, and the image format doesn't have the information that you request (such as the image count) in the header. If you read from a file, simply use

File f = . . .;
ImageInputStream imageIn = ImageIO.createImageInputStream(f);
reader.setInput(imageIn);

Once you have a reader, you can read the images in the input by calling

BufferedImage image = reader.read(index);

where index is the image index, starting with 0.

If the input is in "seek forward only" mode, you need to keep reading images until the read method throws an IndexOutOfBoundsException. Otherwise, you can call the getNumImages method:

int n = reader.getNumImages(true);

Here, the parameter indicates that you allow a search of the input to determine the number of images. That method throws an IllegalStateException if the input is in "seek forward only" mode. Alternatively, you can set the "allow search" parameter to false. Then the getNumImages method returns -1 if it can't determine the number of images without a search. In that case, you'll have to switch to Plan B and keep reading images until you get an IndexOutOfBoundsException.

Some files contain thumbnails, smaller versions of an image for preview purposes. You can get the number of thumbnails of an image with the call

int count = reader.getNumThumbnails(index);

Then you get a particular index as

BufferedImage thumbnail = reader.getThumbnail(index,
   thumbnailIndex);

Another consideration is that you sometimes want to get the image size before actually getting the image, in particular, if the image comes from a slow network connection. Use

the calls

int width = reader.getWidth(index);
int height = reader.getHeight(index);

to get the dimensions of an image with a given index. The image dimensions should be available before the actual image data. If there is no image with the given index, the methods throw an IndexOutOfBoundsException.

To write a file with multiple images, you first need an ImageWriter. The IOImage class can enumerate the writers that are capable of writing a particular image format:

String format = . . .;
ImageWriter writer = null;
Iterator iter = IOImage.getImageWritersByFormatName(format);
if (iter.hasNext()) writer = (ImageWriter)iter.next();

Next, turn an output stream or file into an ImageOutputStream and attach it to the writer. For example,

File f = . . .;
ImageOutputStream imageOut = ImageIO.createImageOutputStream(f);
writer.setOutput(imageOut);

You need to wrap each image into an IIOImage object. You can optionally supply a list of thumbnails and image metadata (such as compression algorithms and color information). In this example, we just use null for both; see the SDK documentation for additional information.

IIOImage iioImage = new IIOImage(images[i], null, null);

Write out the first image using the write method:

writer.write(new IIOImage(images[0], null, null));

For subsequent images, use

if (writer.canInsertImage(i))
   writer.writeInsert(i, iioImage, null);

The third parameter can contain an ImageWriteParam object to set image writing details such as tiling and compression; use null for default values.

Not all file formats can handle multiple images. In that case, the canInsertImage method returns false for i > 0, and only a single image is saved.

The program in Example 7-9 lets you load and save files in the formats for which the SDK supplies readers and writers. The program displays multiple images (see Figure 7-29), but not thumbnails.

Figure 7-29. An Animated GIF Image

graphics/07fig29.gif
 

Example 7-9 ImageIOTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.image.*;
  4. import java.io.*;
  5. import java.util.*;
  6. import java.util.List;
  7. import javax.imageio.*;
  8. import javax.imageio.stream.*;
  9. import javax.swing.*;
 10.
 11. /**
 12.    This program lets you read and write image files in the
 13.    formats that the SDK supports. Multi-file images are
 14.    supported.
 15. */
 16. public class ImageIOTest
 17. {
 18.    public static void main(String[] args)
 19.    {
 20.       JFrame frame = new ImageIOFrame();
 21.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 22.       frame.show();
 23.    }
 24. }
 25.
 26. /**
 27.    This frame displays the loaded images. The menu has items
 28.    for loading and saving files.
 29. */
 30. class ImageIOFrame extends JFrame
 31. {
 32.    public ImageIOFrame()
 33.    {
 34.       setTitle("ImageIOTest");
 35.       setSize(WIDTH, HEIGHT);
 36.
 37.       JMenu fileMenu = new JMenu("File");
 38.       JMenuItem openItem = new JMenuItem("Open");
 39.       openItem.addActionListener(new
 40.          ActionListener()
 41.          {
 42.             public void actionPerformed(ActionEvent event)
 43.             {
 44.                openFile();
 45.             }
 46.          });
 47.       fileMenu.add(openItem);
 48.
 49.       JMenu saveMenu = new JMenu("Save");
 50.       fileMenu.add(saveMenu);
 51.       Iterator iter = writerFormats.iterator();
 52.       while (iter.hasNext())
 53.       {
 54.          final String formatName = (String)iter.next();
 55.          JMenuItem formatItem = new JMenuItem(formatName);
 56.          saveMenu.add(formatItem);
 57.          formatItem.addActionListener(new
 58.             ActionListener()
 59.             {
 60.                public void actionPerformed(ActionEvent event)
 61.                {
 62.                   saveFile(formatName);
 63.                }
 64.             });
 65.       }
 66.
 67.       JMenuItem exitItem = new JMenuItem("Exit");
 68.       exitItem.addActionListener(new
 69.          ActionListener()
 70.          {
 71.             public void actionPerformed(ActionEvent event)
 72.             {
 73.                 System.exit(0);
 74.             }
 75.          });
 76.       fileMenu.add(exitItem);
 77.
 78.
 79.       JMenuBar menuBar = new JMenuBar();
 80.       menuBar.add(fileMenu);
 81.       setJMenuBar(menuBar);
 82.    }
 83.
 84.    /**
 85.       Open a file and load the images.
 86.    */
 87.    public void openFile()
 88.    {
 89.       JFileChooser chooser = new JFileChooser();
 90.       chooser.setCurrentDirectory(new File("."));
 91.
 92.       chooser.setFileFilter(new
 93.          javax.swing.filechooser.FileFilter()
 94.          {
 95.             public boolean accept(File f)
 96.             {
 97.                if (f.isDirectory()) return true;
 98.                String name = f.getName();
 99.                int p = name.lastIndexOf('.');
100.                if (p == -1) return false;
101.                String suffix
102.                   = name.substring(p + 1).toLowerCase();
103.                return readerSuffixes.contains(suffix);
104.             }
105.             public String getDescription()
106.             {
107.                return "Image files";
108.             }
109.          });
110.       int r = chooser.showOpenDialog(this);
111.       if (r != JFileChooser.APPROVE_OPTION) return;
112.       File f = chooser.getSelectedFile();
113.       Box box = Box.createVerticalBox();
114.       try
115.       {
116.          String name = f.getName();
117.          String suffix
118.             = name.substring(name.lastIndexOf('.') + 1);
119.          Iterator iter
120.             = ImageIO.getImageReadersByFormatName(suffix);
121.          ImageReader reader = (ImageReader)iter.next();
122.          ImageInputStream imageIn
123.              = ImageIO.createImageInputStream(f);
124.          reader.setInput(imageIn);
125.          int count = reader.getNumImages(true);
126.          images = new BufferedImage[count];
127.          for (int i = 0; i < count; i++)
128.          {
129.             images[i] = reader.read(i);
130.             box.add(new JLabel(new ImageIcon(images[i])));
131.          }
132.       }
133.       catch (IOException exception)
134.       {
135.          JOptionPane.showMessageDialog(this, exception);
136.       }
137.       setContentPane(new JScrollPane(box));
138.       validate();
139.    }
140.
141.    /**
142.       Save the current image in a file
143.       @param formatName the file format
144.    */
145.    public void saveFile(final String formatName)
146.    {
147.       if (images == null) return;
148.       Iterator iter = ImageIO.getImageWritersByFormatName(
149.          formatName);
150.       ImageWriter writer = (ImageWriter)iter.next();
151.       final List writerSuffixes = Arrays.asList(
152.          writer.getOriginatingProvider().getFileSuffixes());
153.       JFileChooser chooser = new JFileChooser();
154.       chooser.setCurrentDirectory(new File("."));
155.
156.       chooser.setFileFilter(new
157.          javax.swing.filechooser.FileFilter()
158.          {
159.             public boolean accept(File f)
160.             {
161.                if (f.isDirectory()) return true;
162.                String name = f.getName();
163.                int p = name.lastIndexOf('.');
164.                if (p == -1) return false;
165.                String suffix
166.                   = name.substring(p + 1).toLowerCase();
167.                return writerSuffixes.contains(suffix);
168.             }
169.             public String getDescription()
170.             {
171.                return formatName + " files";
172.             }
173.          });
174.
175.       int r = chooser.showSaveDialog(this);
176.       if (r != JFileChooser.APPROVE_OPTION) return;
177.       File f = chooser.getSelectedFile();
178.       try
179.       {
180.          ImageOutputStream imageOut
181.             = ImageIO.createImageOutputStream(f);
182.          writer.setOutput(imageOut);
183.
184.          writer.write(new IIOImage(images[0], null, null));
185.          for (int i = 1; i < images.length; i++)
186.          {
187.             IIOImage iioImage
188.                = new IIOImage(images[i], null, null);
189.             if (writer.canInsertImage(i))
190.                writer.writeInsert(i, iioImage, null);
191.          }
192.       }
193.       catch (IOException exception)
194.       {
195.          JOptionPane.showMessageDialog(this, exception);
196.       }
197.    }
198.
199.    /**
200.       Gets a set of all file suffixes that are recognized
201.       by image readers.
202.       @return the file suffix set
203.    */
204.    public static Set getReaderSuffixes()
205.    {
206.       TreeSet readerSuffixes = new TreeSet();
207.       String[] informalNames = ImageIO.getReaderFormatNames();
208.       for (int i = 0; i < informalNames.length; i++)
209.       {
210.          Iterator iter = ImageIO.getImageReadersByFormatName(
211.             informalNames[i]);
212.          while (iter.hasNext())
213.          {
214.             ImageReader reader = (ImageReader)iter.next();
215.             String[] s = reader.getOriginatingProvider()
216.                .getFileSuffixes();
217.             readerSuffixes.addAll(Arrays.asList(s));
218.          }
219.       }
220.       return readerSuffixes;
221.    }
222.
223.    /**
224.       Gets a set of "preferred" format names of all
225.       image writers. The preferred format name is the first
226.       format name that a writer specifies.
227.       @return the format name set
228.    */
229.    public static Set getWriterFormats()
230.    {
231.       TreeSet writerFormats = new TreeSet();
232.       TreeSet formatNames = new TreeSet(Arrays.asList(
233.          ImageIO.getWriterFormatNames()));
234.       while (formatNames.size() > 0)
235.       {
236.          String name = (String)formatNames.iterator().next();
237.          Iterator iter = ImageIO.getImageWritersByFormatName(
238.             name);
239.          ImageWriter writer = (ImageWriter)iter.next();
240.          String[] names = writer.getOriginatingProvider()
241.             .getFormatNames();
242.          writerFormats.add(names[0]);
243.          formatNames.removeAll(Arrays.asList(names));
244.       }
245.       return writerFormats;
246.    }
247.
248.    private BufferedImage[] images;
249.    private static Set readerSuffixes = getReaderSuffixes();
250.    private static Set writerFormats = getWriterFormats();
251.    private static final int WIDTH = 400;
252.    private static final int HEIGHT = 400;
253.  }
javax.imageio.ImageIO

graphics/api.gif
 

javax.imageio.ImageReader

graphics/api.gif
 

javax.imageio.spi.IIOServiceProvider

graphics/api.gif
 

javax.imageio.spi.ImageReaderWriterSpi

graphics/api.gif
 

javax.imageio.ImageWriter

graphics/api.gif
 

javax.imageio.IIOImage

graphics/api.gif
 

Image Manipulation

Suppose you have an image and you would like to improve its appearance. You then need to access the individual pixels of the image and replace them with other pixels. Or perhaps you want to compute the pixels of an image from scratch, for example, to show the result of physical measurements or a mathematical computation. The BufferedImage class gives you control over the pixels in an image, and classes that implement the BufferedImageOp interface let you transform images.

This is a major change from the image support in JDK 1.0. At that time, the image classes were optimized to support incremental rendering. The original purpose of the classes was to render GIF and JPEG images that are downloaded from the web, a scan line at a time, as soon as partial image data is available. In fact, scan lines can be interlaced, with all even scan lines coming first, followed by the odd scan lines. That mechanism lets a browser display an approximation of the image quickly while fetching the remainder of the image data. The ImageProducer, ImageFilter, and ImageConsumer interfaces in JDK 1.0 expose all the complexities of incremental rendering. Writing an image manipulation that fit well into that framework was quite complex.

Fortunately, the need for using these classes has completely gone away. The Java 2 platform replaces the "push model" of JDK 1.0 with a "direct" model that lets you access pixels directly and conveniently. We cover only the direct model in this chapter. The only disadvantage of the direct model is that it requires all image pixels to be in memory. (In practice, the "push model" had the same restriction. It would have required fiendish cunning to write image manipulation algorithms that processed pixels as they became available. Most users of the old model simply buffered the entire image before processing it.) Future versions of the Java platform may support a "pull" model where a processing pipeline can reduce memory consumption and increase speed by fetching and processing pixels only when they are actually needed.

Accessing Image Data

Most of the images that you manipulate are simply read in from an image file—they were either produced by a device such as a digital camera or scanner, or constructed by a drawing program. In this section, we will show you a different technique for constructing an image, namely, to build up an image a pixel at a time.

To create an image, construct a BufferedImage object in the usual way.

image = new BufferedImage(width, height,
   BufferedImage.TYPE_INT_ARGB);

Now, call the getRaster method to obtain an object of type WritableRaster. You use this object to access and modify the pixels of the image.

WritableRaster raster = image.getRaster();

The setPixel method lets you set an individual pixel. The complexity here is that you can't simply set the pixel to a Color value. You must know how the buffered image specifies color values. That depends on the type of the image. If your image has a type of TYPE_INT_ARGB, then each pixel is described by four values, for red, green, blue, and alpha, each of which is between 0 and 255. You need to supply them in an array of four integers.

int[] black = { 0, 0, 0, 255 };
raster.setPixel(i, j, black);

In the lingo of the Java 2D API, these values are called the sample values of the pixel.

CAUTION

graphics/caution.gif
 

There are also setPixel methods that take array parameters of types float[] and double[]. However, the values that you need to place into these arrays are not normalized color values between 0.0 and 1.0.

float[] red = { 1.0F, 0.0F, 0.0F, 1.0F };
raster.setPixel(i, j, red); // ERROR

You need to supply values between 0 and 255, no matter what the type of the array is.

You can supply batches of pixels with the setPixels method. Specify the starting pixel position and the width and height of the rectangle that you want to set. Then, supply an array that contains the sample values for all pixels. For example, if your buffered image has a type of TYPE_INT_ARGB, then you supply the red, green, blue, and alpha value of the first pixel, then the red, green, blue, and alpha value for the second pixel, and so on.

int[] pixels = new int[4 * width * height];
pixels[0] = . . . // red value for first pixel
pixels[1] = . . . // green value for first pixel
pixels[2] = . . . // blue value for first pixel
pixels[3] = . . . // alpha value for first pixel
. . .
raster.setPixels(x, y, width, height, pixels);

Conversely, to read a pixel, you use the getPixel method. Supply an array of four integers to hold the sample values.

int[] sample = new int[4];
raster.getPixel(x, y, sample);
Color c = new Color(sample[0], sample[1], sample[2], sample[3]);

You can read multiple pixels with the getPixels method.

raster.getPixels(x, y, width, height, samples);

If you use an image type other than TYPE_INT_ARGB and you know how that type represents pixel values, then you can still use the getPixel/setPixel methods. However, you have to know the encoding of the sample values in the particular image type.

If you need to manipulate an image with an arbitrary, unknown image type, then you have to work a bit harder. Every image type has a color model that can translate between sample value arrays and the standard RGB color model.

NOTE

graphics/note.gif
 

The RGB color model isn't as standard as you might think. The exact look of a color value depends on the characteristics of the imaging device. Digital cameras, scanners, monitors, and LCD displays all have their own idiosyncrasies. As a result, the same RGB value can look quite different on different devices. The International Color Consortium (www.color.org) recommends that all color data be accompanied by an ICC profile that specifies how the colors map to a standard form such as the 1931 CIE XYZ color specification. That specification was designed by the Commission Internationale de l'Eclairage or CIE (www.cie.co.at/cie), the international organization in charge of providing technical guidance in all matters of illumination and color. The specification is a standard method for representing all colors that the human eye can perceive as a triple of coordinates called X, Y, Z. (See, for example, Foley, van Dam, Feiner, et al., Chapter 13, for more information on the 1931 CIE XYZ specification.) However, ICC profiles are complex. A simpler proposed standard, called sRGB (http://www.w3.org/Graphics/Color/sRGB.html), specifies an exact mapping between RGB values and the 1931 CIE XYZ values that was designed to work well with typical color monitors. The Java 2D API uses that mapping when converting between RGB and other color spaces.

The getColorModel method returns the color model.

ColorModel model = image.getColorModel();

To find the color value of a pixel, you call the getDataElements method of the Raster class. That call returns an Object that contains a color-model-specific description of the color value.

Object data = raster.getDataElements(x, y, null);

NOTE

graphics/note.gif
 

The object that is returned by the getDataElements method is actually an array of sample values. You don't need to know this to process the object, but it explains why the method is called getDataElements.

The color model can translate the object to standard ARGB values. The getRGB method returns an int value that has the alpha, red, green, and blue values packed in four blocks of 8 bits each. You can construct a Color value out of that integer with the Color(int argb, boolean hasAlpha) constructor.

int argb = model.getRGB(data);
Color color = new Color(argb, true);

When you want to set a pixel to a particular color, you have to reverse these steps. The getRGB method of the Color class yields an int value with the alpha, red, green, and blue values. Supply that value to the getDataElements method of the ColorModel class. The return value is an Object that contains the color-model-specific description of the color value. Pass the object to the setDataElements method of the WritableRaster class.

int argb = color.getRGB();
Object data = model.getDataElements(argb, null);
raster.setDataElements(x, y, data);

To illustrate how to use these methods to build an image from individual pixels, we bow to tradition and draw a Mandelbrot set, as shown in Figure 7-30.

Figure 7-30. A Mandelbrot set

graphics/07fig30.gif
 

The idea of the Mandelbrot set is that you associate with each point in the plane a sequence of numbers. If that sequence stays bounded, you color the point. If it "escapes to infinity," you leave it transparent. The formulas for the number sequences come ultimately from the mathematics of complex numbers. We just take them for granted. For more on the mathematics of fractals, there are hundreds of books out there; one that is quite thick and comprehensive is Chaos and Fractals: New Frontiers of Science by Heinz-Otto Peitgen, Dietmar Saupe, and Hartmut Jurgens [Springer Verlag 1992].

Here is how you can construct the simplest Mandelbrot set. For each point (a,b), you look at sequences that start with (x, y) = (0, 0) and iterate:

graphics/07equ01.gif

graphics/07equ02.gif
 

Check whether the sequence stays bounded or "escapes to infinity," that is, whether x and y keep getting larger. It turns out that if x or y ever get larger than 2, then the sequence escapes to infinity. Only the pixels that correspond to points (a,b) leading to a bounded sequence are colored.

Example 7-10 shows the code. In this program, we demonstrate how to use the ColorModel class for translating Color values into pixel data. That process is independent of the image type. Just for fun, change the color type of the buffered image to TYPE_BYTE_GRAY. You don't need to change any other code—the color model of the image automatically takes care of the conversion from colors to sample values.

Example 7-10 MandelbrotTest.java
 1. import java.awt.*;
 2. import java.awt.event.*;
 3. import java.awt.image.*;
 4. import javax.swing.*;
 5.
 6. /**
 7.    This program demonstrates how to build up an image from
 8.    individual pixels.
 9. */
10. public class MandelbrotTest
11. {
12.    public static void main(String[] args)
13.    {
14.       JFrame frame = new MandelbrotFrame();
15.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
16.       frame.show();
17.    }
18. }
19.
20. /**
21.    This frame shows an image with a Mandelbrot set.
22. */
23. class MandelbrotFrame extends JFrame
24. {
25.    public MandelbrotFrame()
26.    {
27.       setTitle("MandelbrotTest");
28.       setSize(WIDTH, HEIGHT);
29.       BufferedImage image = makeMandelbrot(WIDTH, HEIGHT);
30.       getContentPane().add(new JLabel(new ImageIcon(image)),
31.          BorderLayout.CENTER);
32.    }
33.
34.    /**
35.       Makes the Mandelbrot image.
36.       @param width the width
37.       @parah height the height
38.       @return the image
39.    */
40.    public BufferedImage makeMandelbrot(int width, int height)
41.    {
42.       BufferedImage image = new BufferedImage(width, height,
43.          BufferedImage.TYPE_INT_ARGB);
44.       WritableRaster raster = image.getRaster();
45.       ColorModel model = image.getColorModel();
46.
47.       Color fractalColor = Color.red;
48.       int argb = fractalColor.getRGB();
49.       Object colorData = model.getDataElements(argb, null);
50.
51.       for (int i = 0; i < width; i++)
52.          for (int j = 0; j < height; j++)
53.          {
54.             double a = XMIN + i * (XMAX - XMIN) / width;
55.             double b = YMIN + j * (YMAX - YMIN) / height;
56.             if (!escapesToInfinity(a, b))
57.                raster.setDataElements(i, j, colorData);
58.          }
59.       return image;
60.    }
61.
62.    private boolean escapesToInfinity(double a, double b)
63.    {
64.       double x = 0. 0;
65.       double y = 0. 0;
66.       int iterations = 0;
67.       do
68.       {
69.          double xnew = x * x - y * y + a;
70.          double ynew = 2 * x * y + b;
71.          x = xnew;
72.          y = ynew;
73.          iterations++;
74.          if (iterations == MAX_ITERATIONS) return false;
75.       }
76.       while (x <= 2 && y <= 2);
77.       return true;
78.    }
79.
80.    private static final double XMIN = -2;
81.    private static final double XMAX = 2;
82.    private static final double YMIN = -2;
83.    private static final double YMAX = 2;
84.    private static final int MAX_ITERATIONS = 16;
85.    private static final int WIDTH = 400;
86.    private static final int HEIGHT = 400;
87. }
java.awt.image.BufferedImage

graphics/api.gif
 

java.awt.image.Raster

graphics/api.gif
 

java.awt.image.WritableRaster

graphics/api.gif
 

java.awt.image.ColorModel

graphics/api.gif
 

java.awt.Color

graphics/api.gif
 

Filtering Images

In the preceding section, you saw how to build up an image from scratch. However, often you want to access image data for a different reason: you already have an image and you want to improve it in some way.

Of course, you can use the getPixel/getDataElements methods that you saw in the preceding section to read the image data, manipulate them, and then write them back. But fortunately, Java 2 technology already supplies a number of filters that carry out common image processing operations for you.

The image manipulations all implement the BufferedImageOp interface. After you construct the operation, you simply call the filter method to transform an image into another.

BufferedImageOp op = . . .;
BufferedImage filteredImage
   = new BufferedImage(image.getWidth(), image.getHeight(),
       image.getType());
op.filter(image, filteredImage);

Some operations can transform an image in place (op.filter(image, image)), but most can't.

There are five classes that implement the BufferedImageOp interface:

AffineTransformOp
RescaleOp
LookupOp
ColorConvertOp
ConvolveOp

The AffineTransformOp carries out an affine transformation on the pixels. For example, here is how you can rotate an image about its center.

AffineTransform transform
   = AffineTransform.getRotateInstance(Math.toRadians(angle),
      image.getWidth() / 2, image.getHeight() / 2);
AffineTransformOp op
   = new AffineTransformOp(transform, interpolation);
op.filter(image, filteredImage);

The AffineTransformOp constructor requires an affine transform and an interpolation strategy. Interpolation is necessary to determine pixels in the target image if the source pixels are transformed somewhere between target pixels. For example, if you rotate source pixels, then they will generally not fall exactly onto target pixels. There are two interpolation strategies: AffineTransformOp.TYPE_BILINEAR and AffineTransformOp TYPE_NEAREST_NEIGHBOR. Bilinear interpolation takes a bit longer but looks better.

The program in Example 7-11 lets you rotate an image by 5 degrees (see Figure 7-31).

Figure 7-31. A rotated image

graphics/07fig31.gif
 

The RescaleOp carries out a rescaling operation

graphics/07equ03.gif
 

for all sample values x in the image. Sample values that are too large or small after the rescaling are set to the largest or smallest legal value. If the image is in ARGB format, the scaling is carried out separately for the red, green, and blue values, but not for the alpha values. The effect of rescaling with a > 1 is to brighten the image. You construct the RescaleOp by specifying the scaling parameters and optional rendering hints. In Example 7-11, we use

float a = 1.5f;
float b = -20.0f;
RescaleOp op = new RescaleOp(a, b, null);

The LookupOp operation lets you specify an arbitrary mapping of sample values. You supply a table that specifies how each value should be mapped. In the example program, we compute the negative of all colors, changing the color c to 255 — c.

The LookupOp constructor requires an object of type LookupTable and a map of optional hints. The LookupTable class is abstract. There are two concrete subclasses: ByteLookupTable and ShortLookupTable. Since RGB color values are bytes, we use the ByteLookupTable. You construct such a table from an array of bytes and an integer offset into that array. Here is how we construct the LookupOp for the example program.

byte negative[] = new byte[256];
for (int i = 0; i < 256; i++)
   negative[i] = (byte)(255 - i);
ByteLookupTable table = new ByteLookupTable(0, negative);
LookupOp op = new LookupOp(table, null);

The lookup is applied to each color value separately, but not to the alpha value.

NOTE

graphics/note.gif
 

You cannot apply a LookupOp to an image with an indexed color model. (In those images, each sample value is an offset into a color palette).

The ColorConvertOp is useful for color space conversions. We do not discuss it here.

The most powerful of the transformations is the ConvolveOp, which carries out a mathematical convolution. We do not want to get too deeply into the mathematical details of convolution, but the basic idea is simple. Consider, for example, the blur filter (see Figure 7-32).

Figure 7-32. Blurring an image

graphics/07fig32.jpg

The blurring is achieved by replacing each pixel with the average value from the pixel and its eight neighbors. Intuitively, it makes sense why this operation would blur out the picture. Mathematically, the averaging can be expressed as a convolution operation with the following kernel:

graphics/07fig32a.gif
 

The kernel of a convolution is a matrix that tells what weights should be applied to the neighboring values. The kernel above leads to a blurred image. A different kernel

graphics/07fig32b.gif
 

carries out edge detection, locating areas of color changes (see Figure 7-33). Edge detection is an important technique for analyzing photographic images.

Figure 7-33. Edge detection

graphics/07fig33.gif
 

To construct a convolution operation, you first set up an array of the values for the kernel and construct a Kernel object. Then, construct a ConvolveOp object from the kernel and use it for filtering.

float[] elements =
   {
      0.0f, -1.0f, 0.0f,
      -1.0f,  4.f, -1.0f,
      0.0f, -1.0f, 0.0f
   };
Kernel kernel = new Kernel(3, 3, elements);
ConvolveOp op = new ConvolveOp(kernel);
op.filter(image, filteredImage);

The program in Example 7-11 allows a user to load in a GIF or JPEG image and to carry out the image manipulations that we discussed. Thanks to the power of the image operations that the Java 2D API provides, the program is very simple.

Example 7-11 ImageProcessingTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.geom.*;
  4. import java.awt.image.*;
  5. import java.io.*;
  6. import javax.imageio.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    This program demonstrates various image processing operations.
 11. */
 12. public class ImageProcessingTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new ImageProcessingFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame has a menu to load an image and to specify
 24.    various transformations, and a panel to show the resulting
 25.    image.
 26. */
 27. class ImageProcessingFrame extends JFrame
 28. {
 29.    public ImageProcessingFrame()
 30.    {
 31.       setTitle("ImageProcessingTest");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       JPanel panel = new
 35.          JPanel()
 36.          {
 37.             public void paintComponent(Graphics g)
 38.             {
 39.                super.paintComponent(g);
 40.                if (image != null)
 41.                   g.drawImage(image, 0, 0, null);
 42.             }
 43.          };
 44.
 45.       getContentPane().add(panel, BorderLayout.CENTER);
 46.
 47.       JMenu fileMenu = new JMenu("File");
 48.       JMenuItem openItem = new JMenuItem("Open");
 49.       openItem.addActionListener(new
 50.          ActionListener()
 51.          {
 52.             public void actionPerformed(ActionEvent event)
 53.             {
 54.                openFile();
 55.             }
 56.          });
 57.       fileMenu.add(openItem);
 58.
 59.       JMenuItem exitItem = new JMenuItem("Exit");
 60.       exitItem.addActionListener(new
 61.          ActionListener()
 62.          {
 63.             public void actionPerformed(ActionEvent event)
 64.             {
 65.                System.exit(0);
 66.             }
 67.          });
 68.       fileMenu.add(exitItem);
 69.
 70.       JMenu editMenu = new JMenu("Edit");
 71.       JMenuItem blurItem = new JMenuItem("Blur");
 72.       blurItem.addActionListener(new
 73.          ActionListener()
 74.          {
 75.             public void actionPerformed(ActionEvent event)
 76.             {
 77.                float weight = 1. 0f/9. 0f;
 78.                float[] elements = new float[9];
 79.                for (int i = 0; i < 9; i++)
 80.                   elements[i] = weight;
 81.                convolve(elements);
 82.             }
 83.          });
 84.       editMenu.add(blurItem);
 85.
 86.       JMenuItem sharpenItem = new JMenuItem("Sharpen");
 87.       sharpenItem.addActionListener(new
 88.          ActionListener()
 89.          {
 90.             public void actionPerformed(ActionEvent event)
 91.             {
 92.                float[] elements =
 93.                {  0.0f, -1.0f, 0.0f,
 94.                   -1.0f,  5.f, -1.0f,
 95.                   0.0f, -1.0f, 0.0f
 96.                };
 97.                convolve(elements);
 98.             }
 99.          });
100.       editMenu.add(sharpenItem);
101.
102.       JMenuItem brightenItem = new JMenuItem("Brighten");
103.       brightenItem.addActionListener(new
104.          ActionListener()
105.          {
106.             public void actionPerformed(ActionEvent event)
107.             {
108.                float a = 1. 5f;
109.                float b = -20.  0f;
110.                RescaleOp op = new RescaleOp(a, b, null);
111.                filter(op);
112.             }
113.          });
114.       editMenu.add(brightenItem);
115.
116.       JMenuItem edgeDetectItem = new JMenuItem("Edge detect");
117.       edgeDetectItem.addActionListener(new
118.          ActionListener()
119.          {
120.             public void actionPerformed(ActionEvent event)
121.             {
122.                float[] elements =
123.                {  0.0f, -1.0f, 0.0f,
124.                   -1.0f,  4.f, -1.0f,
125.                   0.0f, -1.0f, 0.0f
126.                };
127.                convolve(elements);
128.             }
129.          });
130.       editMenu.add(edgeDetectItem);
131.
132.       JMenuItem negativeItem = new JMenuItem("Negative");
133.       negativeItem.addActionListener(new
134.          ActionListener()
135.          {
136.             public void actionPerformed(ActionEvent event)
137.             {
138.                byte negative[] = new byte[256];
139.                for (int i = 0; i < 256; i++)
140.                   negative[i] = (byte)(255 - i);
141.                ByteLookupTable table
142.                   = new ByteLookupTable(0, negative);
143.                LookupOp op = new LookupOp(table, null);
144.                filter(op);
145.             }
146.          });
147.       editMenu.add(negativeItem);
148.
149.       JMenuItem rotateItem = new JMenuItem("Rotate");
150.       rotateItem.addActionListener(new
151.          ActionListener()
152.          {
153.             public void actionPerformed(ActionEvent event)
154.             {
155.                AffineTransform transform
156.                   = AffineTransform.getRotateInstance(
157.                      Math.toRadians(5),
158.                      image.getWidth() / 2,
159.                      image.getHeight() / 2);
160.                AffineTransformOp op
161.                   = new AffineTransformOp(transform,
162.                      AffineTransformOp.TYPE_BILINEAR);
163.                filter(op);
164.             }
165.          });
166.       editMenu.add(rotateItem);
167.
168.       JMenuBar menuBar = new JMenuBar();
169.       menuBar.add(fileMenu);
170.       menuBar.add(editMenu);
171.       setJMenuBar(menuBar);
172.    }
173.
174.    /**
175.       Open a file and load the image.
176.    */
177.    public void openFile()
178.    {
179.       JFileChooser chooser = new JFileChooser();
180.       chooser.setCurrentDirectory(new File("."));
181.
182.       chooser.setFileFilter(new
183.          javax.swing.filechooser.FileFilter()
184.          {
185.             public boolean accept(File f)
186.             {
187.                String name = f.getName().toLowerCase();
188.                return name.endsWith(".gif")
189.                   || name.endsWith(".jpg")
190.                   || name.endsWith(".jpeg")
191.                   || f.isDirectory();
192.             }
193.             public String getDescription()
194.             {
195.                return "Image files";
196.             }
197.          });
198.
199.       int r = chooser.showOpenDialog(this);
200.       if(r != JFileChooser.APPROVE_OPTION) return;
201.
202.       try
203.       {
204.          image = ImageIO.read(chooser.getSelectedFile());
205.       }
206.       catch (IOException exception)
207.       {
208.          JOptionPane.showMessageDialog(this, exception);
209.       }
210.       repaint();
211.    }
212.
213.    /**
214.       Apply a filter and repaint.
215.       @param op the image operation to apply
216.    */
217.    private void filter(BufferedImageOp op)
218.    {
219.       BufferedImage filteredImage
220.          = new BufferedImage(image.getWidth(), image.getHeight(),
221.             image.getType());
222.       op.filter(image, filteredImage);
223.       image = filteredImage;
224.       repaint();
225.    }
226.
227.    /**
228.       Apply a convolution and repaint.
229.       @param elements the convolution kernel (an array of
230.       9 matrix elements)
231.    */
232.    private void convolve(float[] elements)
233.    {
234.       Kernel kernel = new Kernel(3, 3, elements);
235.       ConvolveOp op = new ConvolveOp(kernel);
236.       filter(op);
237.    }
238.
239.    private BufferedImage image;
240.    private static final int WIDTH = 400;
241.    private static final int HEIGHT = 400;
242. }
java.awt.image.BufferedImageOp

graphics/api.gif
 

java.awt.image.AffineTransformOp

graphics/api.gif
 

java.awt.image.RescaleOp

graphics/api.gif
 

java.awt.image.LookupOp

graphics/api.gif
 

java.awt.image.ByteLookupTable

graphics/api.gif
 

java.awt.image.ConvolveOp

graphics/api.gif
 

java.awt.image.Kernel

graphics/api.gif
 

Printing

The original Java Development Kit had no support for printing at all. It was not possible to print from applets, and you had to get a third-party library if you wanted to print in an application. SDK 1.1 introduced very lightweight printing support, just enough to produce simple printouts, as long as you were not too particular about the print quality. The 1.1 printing model was designed to allow browser vendors to print the surface of an applet as it appears on a web page (which, however, the browser vendors have not embraced). Apart from that, it is best if the 1.1 printing model sinks into the obscurity it so richly deserves.

SDK 1.2 introduced the beginnings of a robust printing model that is fully integrated with 2D graphics, and SDK 1.3 provided minor improvements. SDK 1.4 adds important enhancements, such as discovery of printer features and streaming print jobs for server-side print management.

In this section, we show you how you can easily print a drawing on a single sheet of paper, how you can manage a multipage printout, and how you can benefit from the elegance of the Java 2D imaging model and easily generate a print preview dialog.

NOTE

graphics/note.gif
 

The Java platform also has support for printing user interface components. We do not cover this topic because it is mostly of interest to implementors of browsers, screen grabbers, and so on. For more information on printing components, see http://java.sun.com/products/jdk/1.1/docs/guide/awt/designspec/printing.html.

Printing Graphics

In this section, we will tackle what is probably the most common printing situation: to print a 2D graphic. Of course, the graphic can contain text in various fonts, or even consist entirely of text.

To generate a printout, you need to take care of these two items:

The Printable interface has a single method:

int print(Graphics g, PageFormat format, int page)

That method is called whenever the print engine needs to have a page formatted for printing. Your code draws the text and image that need to be printed onto the graphics context. The page format tells you the paper size and the print margins. The page number tells you which page you need to render.

To start a print job, you use the PrinterJob class. First, you call the static getPrinterJob method to get a print job object. Then set the Printable object that you want to print.

Printable canvas = . . .;
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(canvas);

CAUTION

graphics/caution.gif
 

There is a class PrintJob that handles JDK 1.1 style printing. That class is now obsolete. Do not confuse it with the PrinterJob class.

Before starting the print job, you should call the printDialog method to display a print dialog (see Figure 7-34). That dialog gives the user a chance to select the printer to be used (in case there are multiple printers available), the page range that should be printed, and various printer settings.

Figure 7-34. A Cross-Platform Print Dialog

graphics/07fig34.gif
 

NOTE

graphics/note.gif
 

At the time of this writing, the Java printing dialogs do not yet work properly on Linux. To print on Linux, you need to generate a PostScript file with the stream print service that is described later in this chapter, and then spool the resulting file.

You collect printer settings in an object of a class that implements the PrintRequestAttributeSet interface to the printDialog method. The SDK provides a HashPrintRequestAttributeSet class for that purpose.

HashPrintRequestAttributeSet attributes
   = new HashPrintRequestAttributeSet();
. . .

Pass the attributes object to the printDialog method.

The printDialog method returns true if the user clicked OK and false if the user canceled the dialog. If the user accepted, call the print method of the PrinterJob class to start the printing process. The print method may throw a PrinterException. Here is the outline of the printing code.

if (job.printDialog(attributes))
{
   try
   {
      job.print();
   }
   catch (PrinterException exception)
   {
      . . .
   }
}

NOTE

graphics/note.gif
 

If you need to support SDK 1.2 or 1.3, you must modify your program to display the native print dialog instead of the cross-platform dialog that was added in SDK 1.4. See the sidebar at the end of this section for details.

During printing, the print method of the PrinterJob class makes repeated calls to the print method of the Printable object associated with the job.

Since the job does not know how many pages you want to print, it simply keeps calling the print method. As long as the print method returns the value Printable.PAGE_EXISTS, the print job keeps producing pages. When the print method returns Printable.NO_SUCH_PAGE, the print job stops.

CAUTION

graphics/caution.gif
 

The page numbers that the print job passes to the print method start with page 0.

Therefore, the print job doesn't have an accurate page count until after the printout is complete. For that reason, the print dialog can't display the correct page range and instead displays a page range of "Pages 1 to 1." You will see in the next section how to avoid this blemish by supplying a Book object to the print job.

During the printing process, the print job repeatedly calls the print method of the Printable object. The print job is allowed to make multiple calls for the same page. You should therefore not count pages inside the print method, but always rely on the page number parameter. There is a good reason why the print job may call the print method repeatedly for the same page. Some printers, in particular dot-matrix and inkjet printers, use banding. They print one band at a time, advance the paper, and then print the next band. The print job may use banding even for laser printers that print a full page at a time—it gives the print job a way of managing the size of the spool file.

If the print job needs the Printable object to print a band, then it sets the clip area of the graphics context to the requested band and calls the print method. Its drawing operations will be clipped against the band rectangle, and only those drawing elements that show up in the band will be rendered. Your print method does not need to be aware of that process, with one caveat: it should not interfere with the clip area.

CAUTION

graphics/caution.gif
 

The Graphics object that your print method gets is also clipped against the page margins. If you replace the clip area, you can draw outside the margins. Especially in a printer graphics context, you need to respect the clipping area. Call clip, not setClip, to further restrict the clipping area. If you must remove a clip area, then make sure to call getClip at the beginning of your print method, and restore that clip area.

The PageFormat parameter of the print method contains information about the printed page. The methods

getWidth
getHeight

return the paper size, measured in points. One point is 1/72 of an inch. (An inch equals 25.4 millimeters.) For example, A4 paper is approximately 595 by 842 points, and US letter-size paper is 612 by 792 points.

Points are a common measurement in the printing trade in the United States. Much to the chagrin of the rest of the world, the printing package uses point units for two purposes. Paper sizes and paper margins are measured in points. And the default unit for all print graphics contexts is one point. You can verify that in the example program at the end of this section. The program prints two lines of text that are 72 units apart from another. Run the example program and measure the distance between the baselines. They are exactly 1 inch or 25.4 millimeters apart.

The getWidth and getHeight methods of the PageFormat class give you the complete paper size. Not all of the paper area is printable. Users typically select margins, and even if they don't, printers need to somehow grip the sheets of paper on which they print and therefore have a small unprintable area around the edges. The methods

getImageableWidth
getImageableHeight

tell you the dimensions of the area that you can actually fill. However, the margins need not be symmetrical, so you also need to know the top-left corner of the imageable area (see Figure 7-35), which is obtained by the methods

Figure 7-35. Page format measurements

graphics/07fig35.gif
 

getImageableX
getImageableY

TIP

graphics/tip.gif
 

The graphics context that you receive in the print method is clipped to exclude the margins. But the origin of the coordinate system is nevertheless the top-left corner of the paper. It makes sense to translate the coordinate system to start at the top-left corner of the imageable area. Simply start your print method with

g.translate(pageFormat.getImageableX(),
   pageFormat.getImageableY());

If you want to have your users choose the settings for the page margins or have them switch between portrait and landscape orientation without setting other printing attributes, then you can call the pageDialog method of the PrinterJob class:

PageFormat format = job.pageDialog(attributes);

NOTE

graphics/note.gif
 

One of the tabs of the print dialog contains the page setup dialog (see Figure 7-36). You may still want to give users an option to set the page format before printing, especially if your program presents a "what you see is what you get" display of the pages to be printed. The pageDialog method returns a PageFormat object with the user settings.

Figure 7-36. A Cross-Platform Page Setup Dialog

graphics/07fig36.gif
 

Example 7-12 shows you how to render the same set of shapes on the screen and on the printed page. A subclass of JPanel implements the Printable interface. Both the paintComponent and the print methods call the same method to carry out the actual drawing.

class PrintPanel extends JPanel implements Printable
{
   public void paintComponent(Graphics g)
   {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
      drawPage(g2);
   }

   public int print(Graphics g, PageFormat pf, int page)
      throws PrinterException
   {
      if (page >= 1) return Printable.NO_SUCH_PAGE;
      Graphics2D g2 = (Graphics2D)g;
      g2.translate(pf.getImageableX(), pf.getImageableY());
      drawPage(g2);
      return Printable.PAGE_EXISTS;
   }

   public void drawPage(Graphics2D g2)
   {
      // shared drawing code goes here
      . . .
   }
   . . .
}

CAUTION

graphics/caution.gif
 

SDK 1.2 does not set the paint to black when setting up a printer graphics context. If your pages come out all white, add a line g2.setPaint(Color.black) at the top of the print method. This problem has been fixed in SDK 1.3.

This example displays and prints the same image as Example 7-6 , namely the outline of the message "Hello, World" that is used as a clipping area for a pattern of lines (see Figure 7-22).

Click on the Print button to start printing, or on the Page setup button to bring up the page setup dialog. Example 7-12 shows the code.

Using Native Print Dialogs

Prior to SDK 1.4, the printing system used the native print and page setup dialogs of the host platform. To show a native print dialog, call the printDialog method with no parameters. (There is no way to collect user settings in an attribute set.) Figure 7-37 shows a Windows print dialog.

Figure 7-37. A Windows print dialog

graphics/07fig37.gif
 

One potential advantage of using the native print dialog is that some printer drivers have special features that are not accessible through the cross-platform dialog. At any rate, if you want to support SDK 1.2 and 1.3, you need to show the native dialogs.

To show a native page setup dialog, you pass a default PageFormat object to the pageDialog method. The method clones that object, modifies it according to the user selections in the dialog, and returns the cloned object.

PageFormat defaultFormat = printJob.defaultPage();
PageFormat selectedFormat = printJob.pageDialog(defaultFormat);

Figure 7-38 shows a page setup dialog for the Windows operating system.

Figure 7-38. A Windows page setup dialog

graphics/07fig38.gif
 

Example 7-12 PrintTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.font.*;
  4. import java.awt.geom.*;
  5. import java.awt.print.*;
  6. import java.util.*;
  7. import javax.print.*;
  8. import javax.print.attribute.*;
  9. import javax.swing.*;
 10.
 11. /**
 12.    This program demonstrates how to print 2D graphics
 13. */
 14. public class PrintTest
 15. {
 16.    public static void main(String[] args)
 17.    {
 18.       JFrame frame = new PrintTestFrame();
 19.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 20.       frame.show();
 21.    }
 22. }
 23.
 24. /**
 25.    This frame shows a panel with 2D graphics and buttons
 26.    to print the graphics and to set up the page format.
 27. */
 28. class PrintTestFrame extends JFrame
 29. {
 30.    public PrintTestFrame()
 31.    {
 32.       setTitle("PrintTest");
 33.       setSize(WIDTH, HEIGHT);
 34.
 35.       Container contentPane = getContentPane();
 36.       canvas = new PrintPanel();
 37.       contentPane.add(canvas, BorderLayout.CENTER);
 38.
 39.       attributes = new HashPrintRequestAttributeSet();
 40.
 41.       JPanel buttonPanel = new JPanel();
 42.       JButton printButton = new JButton("Print");
 43.       buttonPanel.add(printButton);
 44.       printButton.addActionListener(new
 45.          ActionListener()
 46.          {
 47.             public void actionPerformed(ActionEvent event)
 48.             {
 49.                try
 50.                {
 51.                   PrinterJob job = PrinterJob.getPrinterJob();
 52.                   job.setPrintable(canvas);
 53.                   if (job.printDialog(attributes))
 54.                   {
 55.                      job.print(attributes);
 56.                   }
 57.                }
 58.                catch (PrinterException exception)
 59.                {
 60.                   JOptionPane.showMessageDialog(
 61.                      PrintTestFrame.this, exception);
 62.                }
 63.              }
 64.          });
 65.
 66.       JButton pageSetupButton = new JButton("Page setup");
 67.       buttonPanel.add(pageSetupButton);
 68.       pageSetupButton.addActionListener(new
 69.          ActionListener()
 70.          {
 71.             public void actionPerformed(ActionEvent event)
 72.             {
 73.                PrinterJob job = PrinterJob.getPrinterJob();
 74.                job.pageDialog(attributes);
 75.             }
 76.          });
 77.
 78.       contentPane.add(buttonPanel, BorderLayout.NORTH);
 79.    }
 80.
 81.    private PrintPanel canvas;
 82.    private PrintRequestAttributeSet attributes;
 83.
 84.    private static final int WIDTH = 300;
 85.    private static final int HEIGHT = 300;
 86. }
 87.
 88. /**
 89.    This panel generates a 2D graphics image for screen display
 90.    and printing.
 91. */
 92. class PrintPanel extends JPanel implements Printable
 93. {
 94.    public void paintComponent(Graphics g)
 95.    {
 96.       super.paintComponent(g);
 97.       Graphics2D g2 = (Graphics2D)g;
 98.       drawPage(g2);
 99.    }
100.
101.    public int print(Graphics g, PageFormat pf, int page)
102.       throws PrinterException
103.    {
104.       if (page >= 1) return Printable.NO_SUCH_PAGE;
105.       Graphics2D g2 = (Graphics2D)g;
106.       g2.translate(pf.getImageableX(), pf.getImageableY());
107.       g2.draw(new Rectangle2D.Double(0, 0,
108.          pf.getImageableWidth(), pf.getImageableHeight()));
109.
110.       drawPage(g2);
111.       return Printable.PAGE_EXISTS;
112.    }
113.
114.    /**
115.       This method draws the page both on the screen and the
116.       printer graphics context.
117.       @param g2 the graphics context
118.    */
119.    public void drawPage(Graphics2D g2)
120.    {
121.       FontRenderContext context = g2. getFontRenderContext();
122.       Font f = new Font("Serif", Font.PLAIN, 72);
123.       GeneralPath clipShape = new GeneralPath();
124.
125.       TextLayout layout = new TextLayout("Hello", f, context);
126.       AffineTransform transform
127.          = AffineTransform.getTranslateInstance(0, 72);
128.       Shape outline = layout.getOutline(transform);
129.       clipShape.append(outline, false);
130.
131.       layout = new TextLayout("World", f, context);
132.       transform
133.          = AffineTransform.getTranslateInstance(0, 144);
134.       outline = layout.getOutline(transform);
135.       clipShape.append(outline, false);
136.
137.       g2.draw(clipShape);
138.       g2.clip(clipShape);
139.
140.       final int NLINES =50;
141.       Point2D p = new Point2D.Double(0, 0);
142.       for (int i = 0; i < NLINES; i++)
143.       {
144.          double x = (2 * getWidth() * i) / NLINES;
145.          double y = (2 * getHeight() * (NLINES - 1 - i))
146.             / NLINES;
147.          Point2D q = new Point2D.Double(x, y);
148.          g2. draw(new Line2D.Double(p, q));
149.       }
150.    }
151. }
java.awt.print.Printable

graphics/api.gif
 

java.awt.print.PrinterJob

graphics/api.gif
 

java.awt.print.PageFormat

graphics/api.gif
 

Printing Multiple Pages

In practice, you don't usually want to pass a raw Printable object to a print job. Instead, you should obtain an object of a class that implements the Pageable interface. The Java platform supplies one such class, called Book. A book is made up of sections, each of which is a Printable. You make a book by adding Printable objects and their page counts.

Book book = new Book();
Printable coverPage = . . .;
Printable bodyPages = . . .;
book.append(coverPage, pageFormat); // append 1 page
book.append(bodyPages, pageFormat, pageCount);

Then, you use the setPageable method to pass the Book object to the print job.

printJob.setPageable(book);

Now the print job knows exactly how many pages to print. Then, the print dialog displays an accurate page range, and the user can select the entire range or subranges.

CAUTION

graphics/caution.gif
 

When the print job calls the print methods of the Printable sections, it passes the current page number of the book, and not of each section, as the current page number. That is a huge pain—each section must know the page counts of the preceding sections to make sense of the page number parameter.

From a programmer's perspective, the biggest challenge about using the Book class is that you need to know how many pages each section will have when you print it. Your Printable class needs a layout algorithm that computes the layout of the material on the printed pages. Before printing starts, invoke that algorithm to compute the page breaks and the page count. You can retain the layout information so you have it handy during the printing process.

You must guard against the possibility that the user has changed the page format. If that happens, you must recompute the layout, even if the information that you want to print has not changed.

Example 7-13 shows how to produce a multipage printout. This program prints a message in very large characters on a number of pages (see Figure 7-39). You can then trim the margins and tape the pages together to form a banner.

Figure 7-39. A banner

graphics/07fig39.gif
 

The layoutPages method of the Banner class computes the layout. We first lay out the message string in a 72-point font. Then, we compute the height of the resulting string and compare it against the imageable height of the page.We derive a scale factor from these two measurements. When printing the string, we will magnify it by that scale factor.

CAUTION

graphics/caution.gif
 

To lay out your information precisely, you usually need access to the printer graphics context. Unfortunately, there is no way to obtain that graphics context until printing actually starts. In our example program, we make do with the screen graphics context and hope that the font metrics of the screen and printer match.

The getPageCount method of the Banner class first calls the layout method. Then it scales up the width of the string and divides it by the imageable width of each page. The quotient, rounded up to the next integer, is the page count.

It sounds like it might be difficult to print the banner since characters can be broken across multiple pages. However, thanks to the power of the Java 2D API, this turns out not to be a problem at all. When a particular page is requested, we simply use the translate method of the Graphics2D class to shift the top-left corner of the string to the left. Then, we set a clip rectangle that equals the current page (see Figure 7-40). Finally, we scale the graphics context with the scale factor that the layout method computed.

Figure 7-40. Printing a page of a banner

graphics/07fig40.gif

This example shows the power of transformations. The drawing code is kept simple, and the transformation does all the work of placing the drawing at the appropriate place. Finally, the clip cuts away the part of the image that falls outside the page. In the next section, you will see another compelling use of transformations, to display a print preview.

Print Preview

Most professional programs have a print preview mechanism that lets you look at your pages on the screen so that you won't waste paper on a printout that you don't like. The printing classes of the Java platform do not supply a standard "print preview" dialog. But it is easy to design your own (see Figure 7-41). In this section, we show you how. The PrintPreviewDialog class in Example 7-13 is completely generic—you can reuse it to preview any kind of printout.

Figure 7-41. A print preview dialog

graphics/07fig41.gif

To construct a PrintPreviewDialog, you supply either a Printable or a Book, together with a PageFormat object. The surface of the dialog contains a PrintPreviewCanvas. As you use the Next and Previous buttons to flip through the pages, the paintComponent method calls the print method of the Printable object for the requested page.

Normally, the print method draws the page context on a printer graphics context. However, we supply the screen graphics context, suitably scaled so that the entire printed page fits inside a small screen rectangle.

float xoff = . . .; // left of page
float yoff = . . .; // top of page
float scale = . . .; // to fit printed page onto screen
g2.translate(xoff, yoff);
g2.scale(scale, scale);
Printable printable = book.getPrintable(currentPage);
printable.print(g2, pageFormat, currentPage);

The print method never knows that it doesn't actually produce printed pages. It simply draws onto the graphics context, thereby producing a microscopic print preview on the screen. This is a very compelling demonstration of the power of the Java 2D imaging model.

Example 7-13 contains the code for the banner printing program and the print preview dialog. Type "Hello, World!" into the text field and look at the print preview, then print out the banner.

Example 7-13 BookTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.font.*;
  4. import java.awt.geom.*;
  5. import java.awt.print.*;
  6. import java.util.*;
  7. import javax.print.*;
  8. import javax.print.attribute.*;
  9. import javax.swing.*;
 10.
 11. /**
 12.    This program demonstrates the printing of a multi-page
 13.    book. It prints a "banner", by blowing up a text string
 14.    to fill the entire page vertically. The program also
 15.    contains a generic print preview dialog.
 16. */
 17. public class BookTest
 18. {
 19.    public static void main(String[] args)
 20.    {
 21.       JFrame frame = new BookTestFrame();
 22.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23.       frame.show();
 24.    }
 25. }
 26.
 27. /**
 28.    This frame has a text field for the banner text and
 29.    buttons for printing, page setup, and print preview.
 30. */
 31. class BookTestFrame extends JFrame
 32. {
 33.    public BookTestFrame()
 34.    {
 35.       setTitle("BookTest");
 36.       setSize(WIDTH, HEIGHT);
 37.
 38.       Container contentPane = getContentPane();
 39.       text = new JTextField();
 40.       contentPane.add(text, BorderLayout.NORTH);
 41.
 42.       attributes = new HashPrintRequestAttributeSet();
 43.
 44.       JPanel buttonPanel = new JPanel();
 45.
 46.       JButton printButton = new JButton("Print");
 47.       buttonPanel.add(printButton);
 48.       printButton.addActionListener(new
 49.          ActionListener()
 50.          {
 51.             public void actionPerformed(ActionEvent event)
 52.             {
 53.                try
 54.                {
 55.                   PrinterJob job = PrinterJob.getPrinterJob();
 56.                   job.setPageable(makeBook());
 57.                   if (job.printDialog(attributes))
 58.                   {
 59.                      job.print(attributes);
 60.                   }
 61.                }
 62.                catch (PrinterException exception)
 63.                {
 64.                   JOptionPane.showMessageDialog(
 65.                      BookTestFrame.this, exception);
 66.                }
 67.             }
 68.          });
 69.
 70.       JButton pageSetupButton = new JButton("Page setup");
 71.       buttonPanel.add(pageSetupButton);
 72.       pageSetupButton.addActionListener(new
 73.          ActionListener()
 74.          {
 75.             public void actionPerformed(ActionEvent event)
 76.             {
 77.                PrinterJob job = PrinterJob.getPrinterJob();
 78.                pageFormat = job.pageDialog(attributes);
 79.             }
 80.          });
 81.
 82.       JButton printPreviewButton = new JButton("Print preview");
 83.       buttonPanel.add(printPreviewButton);
 84.       printPreviewButton.addActionListener(new
 85.          ActionListener()
 86.          {
 87.             public void actionPerformed(ActionEvent event)
 88.             {
 89.                PrintPreviewDialog dialog
 90.                   = new PrintPreviewDialog(makeBook());
 91.                dialog.show();
 92.             }
 93.          });
 94.
 95.       contentPane.add(buttonPanel, BorderLayout.SOUTH);
 96.    }
 97.
 98.    /**
 99.       Makes a book that contains a cover page and the
100.       pages for the banner.
101.    */
102.    public Book makeBook()
103.    {
104.       if (pageFormat == null)
105.       {
106.          PrinterJob job = PrinterJob.getPrinterJob();
107.          pageFormat = job.defaultPage();
108.       }
109.       Book book = new Book();
110.       String message = text.getText();
111.       Banner banner = new Banner(message);
112.       int pageCount
113.          = banner.getPageCount((Graphics2D)getGraphics(),
114.             pageFormat);
115.       book.append(new CoverPage(message + " (" + pageCount
116.          + " pages)"), pageFormat);
117.       book.append(banner, pageFormat, pageCount);
118.       return book;
119.     }
120.
121.     private JTextField text;
122.     private PageFormat pageFormat;
123.     private PrintRequestAttributeSet attributes;
124.
125.     private static final int WIDTH = 300;
126.     private static final int HEIGHT = 100;
127. }
128.
129. /**
130.    A banner that prints a text string on multiple pages.
131. */
132. class Banner implements Printable
133.  {
134.    /**
135.       Constructs a banner
136.       @param m the message string
137.    */
138.    public Banner(String m)
139.    {
140.       message = m;
141.    }
142.
143.    /**
144.       Gets the page count of this section.
145.       @param g2 the graphics context
146.       @param pf the page format
147.       @return the number of pages needed
148.    */
149.    public int getPageCount(Graphics2D g2, PageFormat pf)
150.    {
151.       if (message.equals("")) return 0;
152.       FontRenderContext context = g2. getFontRenderContext();
153.       Font f = new Font("Serif", Font.PLAIN, 72);
154.       Rectangle2D bounds = f.getStringBounds(message, context);
155.       scale = pf.getImageableHeight() / bounds.getHeight();
156.       double width = scale * bounds.getWidth();
157.       int pages = (int)Math.ceil(width / pf.getImageableWidth());
158.       return pages;
159.    }
160.
161.    public int print(Graphics g, PageFormat pf, int page)
162.       throws PrinterException
163.    {
164.       Graphics2D g2 = (Graphics2D)g;
165.       if (page > getPageCount(g2, pf))
166.          return Printable.NO_SUCH_PAGE;
167.       g2. translate(pf.getImageableX(), pf.getImageableY());
168.
169.       drawPage(g2, pf, page);
170.       return Printable.PAGE_EXISTS;
171.    }
172.
173.    public void drawPage(Graphics2D g2, PageFormat pf, int page)
174.    {
175.       if (message.equals("")) return;
176.       page--; // account for cover page
177.
178.       drawCropMarks(g2, pf);
179.       g2. clip(new Rectangle2D.Double(0, 0,
180.           pf.getImageableWidth(), pf.getImageableHeight()));
181.       g2. translate(-page * pf.getImageableWidth(), 0);
182.       g2. scale(scale, scale);
183.       FontRenderContext context = g2. getFontRenderContext();
184.       Font f = new Font("Serif", Font.PLAIN, 72);
185.       TextLayout layout = new TextLayout(message, f, context);
186.       AffineTransform transform
187.          = AffineTransform.getTranslateInstance(0,
188.             layout.getAscent());
189.       Shape outline = layout.getOutline(transform);
190.       g2. draw(outline);
191.    }
192.
193.    /**
194.       Draws 1/2" crop marks in the corners of the page.
195.       @param g2 the graphics context
196.       @param pf the page format
197.    */
198.    public void drawCropMarks(Graphics2D g2, PageFormat pf)
199.    {
200.       final double C = 36; // crop mark length = 1/2 inch
201.       double w = pf.getImageableWidth();
202.       double h = pf.getImageableHeight();
203.       g2.draw(new Line2D.Double(0, 0, 0, C));
204.       g2.draw(new Line2D.Double(0, 0, C, 0));
205.       g2.draw(new Line2D.Double(w, 0, w, C));
206.       g2.draw(new Line2D.Double(w, 0, w - C, 0));
207.       g2.draw(new Line2D.Double(0, h, 0, h - C));
208.       g2.draw(new Line2D.Double(0, h, C, h));
209.       g2.draw(new Line2D.Double(w, h, w, h - C));
210.       g2.draw(new Line2D.Double(w, h, w - C, h));
211.    }
212.
213.    private String message;
214.    private double scale;
215. }
216.
217. /**
218.    This class prints a cover page with a title.
219. */
220. class CoverPage implements Printable
221. {
222.    /**
223.       Constructs a cover page.
224.       @param t the title
225.    */
226.    public CoverPage(String t)
227.    {
228.       title = t;
229.    }
230.
231.    public int print(Graphics g, PageFormat pf, int page)
232.       throws PrinterException
233.    {
234.       if (page >= 1) return Printable.NO_SUCH_PAGE;
235.       Graphics2D g2 = (Graphics2D)g;
236.       g2. setPaint(Color.black);
237.       g2. translate(pf.getImageableX(), pf.getImageableY());
238.       FontRenderContext context = g2.getFontRenderContext();
239.       Font f = g2.getFont();
240.       TextLayout layout = new TextLayout(title, f, context);
241.       float ascent = layout.getAscent();
242.       g2.drawString(title, 0, ascent);
243.       return Printable.PAGE_EXISTS;
244.    }
245.
246.    private String title;
247. }
248.
249. /**
250.    This class implements a generic print preview dialog.
251. */
252. class PrintPreviewDialog extends JDialog
253. {
254.    /**
255.       Constructs a print preview dialog.
256.       @param p a Printable
257.       @param pf the page format
258.       @param pages the number of pages in p
259.    */
260.    public PrintPreviewDialog(Printable p, PageFormat pf,
261.       int pages)
262.    {
263.       Book book = new Book();
264.       book.append(p, pf, pages);
265.       layoutUI(book);
266.    }
267.
268.    /**
269.       Constructs a print preview dialog.
270.       @param b a Book
271.    */
272.    public PrintPreviewDialog(Book b)
273.    {
274.       layoutUI(b);
275.    }
276.
277.    /**
278.       Lays out the UI of the dialog.
279.       @param book the book to be previewed
280.    */
281.    public void layoutUI(Book book)
282.    {
283.       setSize(WIDTH, HEIGHT);
284.
285.       Container contentPane = getContentPane();
286.       canvas = new PrintPreviewCanvas(book);
287.       contentPane.add(canvas, BorderLayout.CENTER);
288.
289.       JPanel buttonPanel = new JPanel();
290.
291.       JButton nextButton = new JButton("Next");
292.       buttonPanel.add(nextButton);
293.       nextButton.addActionListener(new
294.          ActionListener()
295.          {
296.            public void actionPerformed(ActionEvent event)
297.            {
298.               canvas.flipPage(1);
299.            }
300.          });
301.
302.       JButton previousButton = new JButton("Previous");
303.       buttonPanel.add(previousButton);
304.       previousButton.addActionListener(new
305.          ActionListener()
306.          {
307.             public void actionPerformed(ActionEvent event)
308.             {
309.                canvas.flipPage(-1);
310.             }
311.          });
312.
313.       JButton closeButton = new JButton("Close");
314.       buttonPanel.add(closeButton);
315.       closeButton.addActionListener(new
316.          ActionListener()
317.          {
318.             public void actionPerformed(ActionEvent event)
319.             {
320.                setVisible(false);
321.             }
322.          });
323.
324.       contentPane.add(buttonPanel, BorderLayout.SOUTH);
325.    }
326.
327.    private PrintPreviewCanvas canvas;
328.
329.    private static final int WIDTH = 300;
330.    private static final int HEIGHT = 300;
331. }
332.
333. /**
334.    The canvas for displaying the print preview.
335. */
336. class PrintPreviewCanvas extends JPanel
337. {
338.    /**
339.       Constructs a print preview canvas.
340.       @param b the book to be previewed
341.    */
342.    public PrintPreviewCanvas(Book b)
343.    {
344.       book = b;
345.       currentPage = 0;
346.    }
347.
348.    public void paintComponent(Graphics g)
349.    {
350.       super.paintComponent(g);
351.       Graphics2D g2 = (Graphics2D)g;
352.       PageFormat pageFormat = book.getPageFormat(currentPage);
353.
354.       double xoff; // x offset of page start in window
355.       double yoff; // y offset of page start in window
356.       double scale; // scale factor to fit page in window
357.       double px = pageFormat.getWidth();
358.       double py = pageFormat.getHeight();
359.       double sx = getWidth() - 1;
360.       double sy = getHeight() - 1;
361.       if (px / py < sx / sy) // center horizontally
362.       {
363.          scale = sy / py;
364.          xoff = 0. 5 * (sx - scale * px);
365.          yoff = 0;
366.       }
367.       else // center vertically
368.       {
369.          scale = sx / px;
370.          xoff = 0;
371.          yoff = 0. 5 * (sy - scale * py);
372.       }
373.       g2. translate((float)xoff, (float)yoff);
374.       g2. scale((float)scale, (float)scale);
375.
376.       // draw page outline (ignoring margins)
377.       Rectangle2D page = new Rectangle2D.Double(0, 0, px, py);
378.       g2.setPaint(Color.white);
379.       g2.fill(page);
380.       g2.setPaint(Color.black);
381.       g2. draw(page);
382.
383.       Printable printable = book.getPrintable(currentPage);
384.       try
385.       {
386.          printable.print(g2, pageFormat, currentPage);
387.       }
388.       catch (PrinterException exception)
389.       {
390.          g2.draw(new Line2D.Double(0, 0, px, py));
391.          g2.draw(new Line2D.Double(0, px, 0, py));
392.       }
393.     }
394.
395.    /**
396.       Flip the book by the given number of pages.
397.       @param by the number of pages to flip by. Negative
398.       values flip backwards.
399.    */
400.    public void flipPage(int by)
401.    {
402.       int newPage = currentPage + by;
403.       if (0 <= newPage && newPage < book.getNumberOfPages())
404.       {
405.          currentPage = newPage;
406.          repaint();
407.       }
408.    }
409.
410.    private Book book;
411.    private int currentPage;
412. }
java.awt.print.PrinterJob

graphics/api.gif
 

java.awt.print.Book

graphics/api.gif
 

Print Services

So far, you have seen how to print 2D graphics. However, the printing API introduced in SDK 1.4 allows for far greater flexibility. The API defines a number of data types and lets you find print services that are able to print them. Among the data types are:

The data themselves can be stored in a source of bytes or characters such as an input stream, a URL, or an array. A document flavor describes the combination of a data source and a data type. The DocFlavor class defines a number of inner classes for the various data sources. Each of the inner classes defines constants to specify the flavors. For example, the constant

DocFlavor.INPUT_STREAM.GIF

describes a GIF image that is read from an input stream. Table 7-3 lists the combinations.

Suppose you want to print a GIF image that is located in a file. You need to find out whether there is a print service that is capable of handling the task. The static lookupPrintServices method of the PrintServiceLookup class returns an array of PrintService objects that can handle the given document flavor.

DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
PrintService[] services
   = PrintServiceLookup.lookupPrintServices(flavor, null);

The second parameter of the lookupPrintServices method is null to indicate that we don't want to constrain the search by specifying printer attributes. We will cover attributes in the next section.

NOTE

graphics/note.gif
 

The SDK 1.4 supplies print services for basic document flavors such as images and 2D graphics. But if you try to print text or HTML documents, the lookup will return an empty array.

If the lookup yields an array with more than one element, you need to pick among the listed print services. You can call the getName method of the PrintService class to get the printer names, and then let the user choose.

Next, get a document print job from the service:

DocPrintJob job = services[i].createPrintJob();
Table 7-3. Document Flavors for Print Services
Data Source Data Type MIME Type
INPUT_STREAM GIF image/gif
URL JPEG image/jpeg
BYTE_ARRAY PNG image/png
  POSTSCRIPT application/postscript
  PDF application/pdf
  TEXT_HTML_HOST text/html (using host encoding)
  TEXT_HTML_US_ASCII

text/html;

charset=us-ascii

  TEXT_HTML_UTF_8

text/html;

charset=utf-8

  TEXT_HTML_UTF_16

text/html;

charset=utf-16

  TEXT_HTML_UTF_16LE

text/html;

charset=utf-16le (little-endian)

  TEXT_HTML_UTF_16BE

text/html;

charset=utf-16le (big-endian)

  TEXT_PLAIN_HOST text/plain (using host encoding)
  TEXT_PLAIN_US_ASCII

text/plain;

charset=us-ascii

  TEXT_PLAIN_UTF_8

text/plain;

charset=utf-8

  TEXT_PLAIN_UTF_16

text/plain;

charset=utf-16

  TEXT_PLAIN_UTF_16LE

text/plain;

charset=utf-16le (little-endian)

  TEXT_PLAIN_UTF_16BE

text/plain;

charset=utf-16be (big-endian)

  PCL application/vnd.hp-PCL (Hewlett Packard Printer Control Language)
  AUTOSENSE application/octet-stream (raw printer data)
READER TEXT_HTML text/html; charset=utf-16
STRING TEXT_PLAIN text/plain; charset=utf-16
CHAR_ARRAY    
SERVICE_FORMATTED PRINTABLE N/A
  PAGEABLE N/A
  RENDERABLE_IMAGE N/A

For printing, you need an object that implements the Doc interface. The SDK supplies a class SimpleDoc for that purpose. The SimpleDoc constructor requires the data source object, the document flavor, and an optional attribute set. For example,

InputStream in = new FileInputStream(fileName);
Doc doc = new SimpleDoc(in, flavor, null);

Finally, you are ready to print:

job.print(doc, null);

As before, the null parameter can be replaced by an attribute set.

Note that this printing process is quite different from that of the preceding section. There isn't any user interaction through print dialogs. For example, you can implement a server-side printing mechanism in which users submit print jobs through a web form.

The program in Example 7-14 demonstrates how to use a print service to print an image file.

Example 7-14 PrintServiceTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.image.*;
  4. import java.io.*;
  5. import java.util.*;
  6. import javax.print.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    This program demonstrates the use of print services.
 11.    The program lets you print a GIF image to any of the print
 12.    services that support the GIF document flavor.
 13. */
 14. public class PrintServiceTest
 15. {
 16.    public static void main(String[] args)
 17.    {
 18.       JFrame frame = new PrintServiceFrame();
 19.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 20.       frame.show();
 21.    }
 22. }
 23.
 24. /**
 25.    This frame displays the image to be printed. It contains
 26.    menus for opening an image file, printing, and selecting
 27.    a print service.
 28. */
 29. class PrintServiceFrame extends JFrame
 30. {
 31.    public PrintServiceFrame()
 32.    {
 33.       setTitle("PrintServiceTest");
 34.       setSize(WIDTH, HEIGHT);
 35.
 36.       // set up menu bar
 37.       JMenuBar menuBar = new JMenuBar();
 38.       setJMenuBar(menuBar);
 39.
 40.       JMenu menu = new JMenu("File");
 41.       menuBar.add(menu);
 42.
 43.       JMenuItem openItem = new JMenuItem("Open");
 44.       menu.add(openItem);
 45.       openItem.addActionListener(new
 46.          ActionListener()
 47.          {
 48.             public void actionPerformed(ActionEvent event)
 49.             {
 50.                openFile();
 51.             }
 52.          });
 53.
 54.       JMenuItem printItem = new JMenuItem("Print");
 55.       menu.add(printItem);
 56.       printItem.addActionListener(new
 57.          ActionListener()
 58.          {
 59.             public void actionPerformed(ActionEvent event)
 60.             {
 61.                printFile();
 62.             }
 63.           });
 64.
 65.       JMenuItem exitItem = new JMenuItem("Exit");
 66.       menu.add(exitItem);
 67.       exitItem.addActionListener(new
 68.          ActionListener()
 69.          {
 70.             public void actionPerformed(ActionEvent event)
 71.             {
 72.                System.exit(0);
 73.             }
 74.          });
 75.
 76.       menu = new JMenu("Printer");
 77.       menuBar.add(menu);
 78.       DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
 79.       addPrintServices(menu, flavor);
 80.
 81.       // use a label to display the images
 82.       label = new JLabel();
 83.       Container contentPane = getContentPane();
 84.       contentPane.add(label);
 85.    }
 86.
 87.    /**
 88.       Adds print services to a menu
 89.       @param menu the menu to which to add the services
 90.       @param flavor the flavor that the services need to support
 91.    */
 92.    public void addPrintServices(JMenu menu, DocFlavor flavor)
 93.    {
 94.       PrintService[] services
 95.          = PrintServiceLookup.lookupPrintServices(flavor, null);
 96.       ButtonGroup group = new ButtonGroup();
 97.       for (int i = 0; i < services.length; i++)
 98.       {
 99.          final PrintService service = services[i];
100.          JRadioButtonMenuItem item
101.             = new JRadioButtonMenuItem(service.getName());
102.          menu.add(item);
103.          if (i == 0)
104.          {
105.             item.setSelected(true);
106.             currentService = service;
107.          }
108.          group.add(item);
109.          item.addActionListener(new
110.             ActionListener()
111.             {
112.                public void actionPerformed(ActionEvent event)
113.                {
114.                   currentService = service;
115.                }
116.             });
117.       }
118.    }
119.
120.    /**
121.       Open a GIF file and display the image.
122.    */
123.    public void openFile()
124.    {
125.       // set up file chooser
126.       JFileChooser chooser = new JFileChooser();
127.       chooser.setCurrentDirectory(new File("."));
128.
129.       // accept all files ending with .gif
130.       chooser.setFileFilter(new
131.          javax.swing.filechooser.FileFilter()
132.          {
133.             public boolean accept(File f)
134.             {
135.                return f.getName().toLowerCase()
136.                   .endsWith(".gif")
137.                   || f.isDirectory();
138.             }
139.             public String getDescription()
140.             {
141.                return "GIF Images";
142.             }
143.          });
144.
145.       // show file chooser dialog
146.       int r = chooser.showOpenDialog(PrintServiceFrame.this);
147.
148.       // if image file accepted, set it as icon of the label
149.       if(r == JFileChooser.APPROVE_OPTION)
150.       {
151.          fileName = chooser.getSelectedFile().getPath();
152.          label.setIcon(new ImageIcon(fileName));
153.       }
154.    }
155.
156.    /**
157.       Print the current file using the current print service.
158.    */
159.    public void printFile()
160.    {
161.       try
162.       {
163.          if (fileName == null) return;
164.          if (currentService == null) return;
165.          FileInputStream in = new FileInputStream(fileName);
166.          DocFlavor flavor = DocFlavor.INPUT_STREAM.GIF;
167.          Doc doc = new SimpleDoc(in, flavor, null);
168.          DocPrintJob job = currentService.createPrintJob();
169.          job.print(doc, null);
170.       }
171.       catch (FileNotFoundException exception)
172.       {
173.          JOptionPane.showMessageDialog(this, exception);
174.       }
175.       catch (PrintException exception)
176.       {
177.          JOptionPane.showMessageDialog(this, exception);
178.       }
179.    }
180.
181.    private JLabel label;
182.    private String fileName;
183.    private PrintService currentService;
184.    private static final int WIDTH = 300;
185.    private static final int HEIGHT = 400;
186. }
javax.print.PrintServiceLookup

graphics/api.gif
 

javax.print.PrintService

graphics/api.gif
 

javax.print.DocPrintJob

graphics/api.gif
 

javax.print.SimpleDoc

graphics/api.gif
 

Stream Print Services

A print service sends print data to a printer. A stream print service generates the same print data but instead sends them to a stream, perhaps for delayed printing or because the print data format can be interpreted by other programs. In particular, if the print data format is PostScript, then it is useful to save the print data to a file since there are many programs that can process PostScript files.

SDK 1.4 includes a stream print service that can produce PostScript output from images and 2D graphics. You can use that service on all systems, even if there are no local printers.

Enumerating stream print services is a bit more tedious than locating regular print services. You need both the DocFlavor of the object to be printed and the MIME type of the stream output. You then get a StreamPrintServiceFactory array of factories.

DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
String mimeType = "application/postscript";
StreamPrintServiceFactory[] factories
   = StreamPrintServiceFactory.lookupStreamPrintServiceFactories
      (flavor, mimeType);

The StreamPrintServiceFactory class doesn't have any methods that would help you distinguish any one factory from another, so we'll just take factories[0]. Call the getPrintService method with an output stream parameter to get a StreamPrintService object.

OutputStream out = new FileOutputStream(fileName);
StreamPrintService service = factories[0].getPrintService(out);

The StreamPrintService class is a subclass of PrintService. To produce a printout, simply follow the steps of the preceding section.

Example 7-15 prints the "Hello, World" graphic from the preceding examples to a PostScript file.

NOTE

graphics/note.gif
 

Unlike the other printing programs, this program works fine on Linux. You can use GhostScript (http://www.cs.wisc.edu/~ghost/) to view or print the resulting output (see Figure 7-42).

Figure 7-42. Viewing a PostScript File

graphics/07fig42.gif
 

Example 7-15 StreamPrintServiceTest.java
  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import java.awt.font.*;
  4. import java.awt.geom.*;
  5. import java.awt.print.*;
  6. import java.io.*;
  7. import java.util.*;
  8. import javax.print.*;
  9. import javax.print.attribute.*;
 10. import javax.swing.*;
 11.
 12.
 13. /**
 14.    This program demonstrates the use of a stream print service.
 15.    It prints a 2D graphic to a PostScript file.
 16. */
 17. public class StreamPrintServiceTest
 18. {
 19.    public static void main(String[] args)
 20.    {
 21.       JFrame frame = new StreamPrintServiceFrame();
 22.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 23.       frame.show();
 24.    }
 25. }
 26.
 27. /**
 28.    This frame shows a panel with 2D graphics and buttons
 29.    to print the graphics to a PostScript file and to set up
 30.    the page format.
 31. */
 32. class StreamPrintServiceFrame extends JFrame
 33. {
 34.    public StreamPrintServiceFrame()
 35.    {
 36.       setTitle("StreamPrintServiceTest");
 37.       setSize(WIDTH, HEIGHT);
 38.
 39.       Container contentPane = getContentPane();
 40.       canvas = new PrintPanel();
 41.       contentPane.add(canvas, BorderLayout.CENTER);
 42.
 43.       attributes = new HashPrintRequestAttributeSet();
 44.
 45.       JPanel buttonPanel = new JPanel();
 46.       JButton printButton = new JButton("Print");
 47.       buttonPanel.add(printButton);
 48.       printButton.addActionListener(new
 49.          ActionListener()
 50.          {
 51.             public void actionPerformed(ActionEvent event)
 52.             {
 53.                String fileName = getFile();
 54.                if (fileName != null)
 55.                   printPostScript(fileName);
 56.             }
 57.          });
 58.
 59.       JButton pageSetupButton = new JButton("Page setup");
 60.       buttonPanel.add(pageSetupButton);
 61.       pageSetupButton.addActionListener(new
 62.          ActionListener()
 63.          {
 64.             public void actionPerformed(ActionEvent event)
 65.             {
 66.                PrinterJob job = PrinterJob.getPrinterJob();
 67.                job.pageDialog(attributes);
 68.             }
 69.          });
 70.
 71.       contentPane.add(buttonPanel, BorderLayout.NORTH);
 72.    }
 73.
 74.    /**
 75.       Allows the user to select a PostScript file.
 76.       @return the file name, or null if the user didn't
 77.       select a file.
 78.    */
 79.    public String getFile()
 80.    {
 81.       // set up file chooser
 82.       JFileChooser chooser = new JFileChooser();
 83.       chooser.setCurrentDirectory(new File("."));
 84.
 85.       // accept all files ending with .ps
 86.       chooser.setFileFilter(new
 87.          javax.swing.filechooser.FileFilter()
 88.          {
 89.             public boolean accept(File f)
 90.             {
 91.                return f.getName().toLowerCase()
 92.                   .endsWith(".ps")
 93.                   || f.isDirectory();
 94.             }
 95.             public String getDescription()
 96.             {
 97.                return "PostScript Files";
 98.             }
 99.          });
100.
101.       // show file chooser dialog
102.       int r = chooser.showSaveDialog(this);
103.
104.       // if file accepted, return path
105.       if(r == JFileChooser.APPROVE_OPTION)
106.          return chooser.getSelectedFile().getPath();
107.       else
108.          return null;
109.    }
110.
111.    /**
112.       Prints the 2D graphic to a PostScript file.
113.       @param fileName the name of the PostScript file
114.    */
115.    public void printPostScript(String fileName)
116.    {
117.       try
118.       {
119.          DocFlavor flavor
120.             = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
121.          String mimeType = "application/postscript";
122.          StreamPrintServiceFactory[] factories =
123.             StreamPrintServiceFactory
124.             .lookupStreamPrintServiceFactories(flavor, mimeType);
125.
126.          FileOutputStream out = new FileOutputStream(fileName);
127.          if (factories.length == 0) return;
128.          StreamPrintService service
129.             = factories[0].getPrintService(out);
130.
131.          Doc doc = new SimpleDoc(canvas, flavor, null);
132.          DocPrintJob job = service.createPrintJob();
133.          job.print(doc, attributes);
134.       }
135.       catch (FileNotFoundException exception)
136.       {
137.          JOptionPane.showMessageDialog(this, exception);
138.       }
139.       catch (PrintException exception)
140.       {
141.          JOptionPane.showMessageDialog(this, exception);
142.       }
143.
144.    }
145.
146.    private PrintPanel canvas;
147.    private PrintRequestAttributeSet attributes;
148.
149.    private static final int WIDTH = 300;
150.    private static final int HEIGHT = 300;
151. }
152.
153. /**
154.    This panel generates a 2D graphics image for screen display
155.    and printing.
156. */
157. class PrintPanel extends JPanel implements Printable
158. {
159.    public void paintComponent(Graphics g)
160.    {
161.       super.paintComponent(g);
162.       Graphics2D g2 = (Graphics2D)g;
163.       drawPage(g2);
164.    }
165.
166.    public int print(Graphics g, PageFormat pf, int page)
167.       throws PrinterException
168.    {
169.       if (page >= 1) return Printable.NO_SUCH_PAGE;
170.       Graphics2D g2 = (Graphics2D)g;
171.       g2.translate(pf.getImageableX(), pf.getImageableY());
172.       g2.draw(new Rectangle2D.Double(0, 0,
173.           pf.getImageableWidth(), pf.getImageableHeight()));
174.
175.       drawPage(g2);
176.       return Printable.PAGE_EXISTS;
177.    }
178.
179.    /**
180.       This method draws the page both on the screen and the
181.       printer graphics context.
182.       @param g2 the graphics context
183.     */
184.    public void drawPage(Graphics2D g2)
185.    {
186.       FontRenderContext context = g2.getFontRenderContext();
187.       Font f = new Font("Serif", Font.PLAIN, 72);
188.       GeneralPath clipShape = new GeneralPath();
189.
190.       TextLayout layout = new TextLayout("Hello", f, context);
191.       AffineTransform transform
192.          = AffineTransform.getTranslateInstance(0, 72);
193.       Shape outline = layout.getOutline(transform);
194.       clipShape.append(outline, false);
195.
196.       layout = new TextLayout("World", f, context);
197.       transform
198.          = AffineTransform.getTranslateInstance(0, 144);
199.       outline = layout.getOutline(transform);
200.       clipShape.append(outline, false);
201.
202.       g2.draw(clipShape);
203.       g2.clip(clipShape);
204.
205.       final int NLINES =50;
206.       Point2D p = new Point2D.Double(0, 0);
207.       for (int i = 0; i < NLINES; i++)
208.       {
209.          double x = (2 * getWidth() * i) / NLINES;
210.          double y = (2 * getHeight() * (NLINES - 1 - i))
211.             / NLINES;
212.          Point2D q = new Point2D.Double(x, y);
213.           g2.draw(new Line2D.Double(p, q));
214.      }
215.    }
216. }
javax.print.StreamPrintServiceFactory

graphics/api.gif
 

Printing Attributes

The print service API contains a complex set of interfaces and classes to specify various kinds of attributes. There are four important groups of attributes. The first two specify requests to the printer.

The other two contain information about the printer and job status.

To describe the various attributes, there is an interface Attribute with subinterfaces:

PrintRequestAttribute
DocAttribute
PrintServiceAttribute
PrintJobAttribute
SupportedValuesAttribute

Individual attribute classes implement one or more of these interfaces. For example, objects of the Copies class are used to describe the number of copies of a printout. That class implements both the PrintRequestAttribute and the PrintJobAttribute interfaces. Clearly, a print request may contain a request for multiple copies. Conversely, an attribute of the print job may be how many of these copies were actually printed. That number might be lower, perhaps because of printer limitations or because the printer ran out of paper.

The SupportedValuesAttribute interface indicates that an attribute value does not reflect actual request or status data but the capability of a service. For example, there is a CopiesSupported class implementing the SupportedValuesAttribute interface. An object of that class might describe that a printer supports 1 through 99 copies of a printout.

Figure 7-43 shows a class diagram of the attribute hierarchy:

Figure 7-43. The Attribute Hierarchy

graphics/07fig43.gif

In addition to the interfaces and classes for individual attributes, the print service API defines interfaces and classes for attribute sets. There is a superinterface AttributeSet with four subinterfaces

PrintRequestAttributeSet
DocAttributeSet
PrintServiceAttributeSet
PrintJobAttributeSet

For each of these interfaces, there is an implementing class, yielding the five classes:

HashAttributeSet
HashPrintRequestAttributeSet
HashDocAttributeSet
HashPrintServiceAttributeSet
HashPrintJobAttributeSet

(See Figure 7-44.) For example, you construct a print request attribute set like this:

Figure 7-44. The Attribute Set Hierarchy

graphics/07fig44.gif
 

PrintRequestAttributeSet attributes
   = new HashPrintRequestAttributeSet();

After constructing the set, you no longer need to worry about the Hash prefix.

Why have all these interfaces? They make it possible to check for correct attribute usage. For example, a DocAttributeSet only accepts objects that implement the DocAttribute interface. Any attempt to add another attribute results in a runtime error.

An attribute set is a very specialized kind of map, where the keys are of type Class and the values belong to a class that implements the Attribute interface. For example, if you insert an object

new Copies(10)

into an attribute set, then its key is the Class object Copies.class. That key is called the category of the attribute. The Attribute interface declares a method

Class getCategory()

that returns the category of an attribute. The Copies class defines the method to return the object Copies.class, but it isn't a requirement that the category is the same as the class of the attribute.

When adding an attribute to an attribute set, the category is extracted automatically. You just add the attribute value:

attributes.add(new Copies(10));

If you subsequently add another attribute with the same category, it overwrites the first one.

To retrieve an attribute, you need to use the category as the key, for example

AttributeSet attributes = job.getAttributes();
Copies copies = (Copies)attribute.get(Copies.class);

Finally, attributes are organized by the values they can have. The Copies attribute can have any integer value. The Copies class extends the IntegerSyntax class which takes care of all integer-valued attributes. The getValue method returns the integer value of the attribute, for example

int n = copies.getValue();

There are also classes

TextSyntax
DateTimeSyntax
URISyntax

that encapsulate a string, date and time, or a URI (Uniform Resource Identifier).

Finally, there are many attributes that can take a finite number of values. For example, the PrintQuality attribute has three settings: draft, normal, and high.

They are represented by three constants:

PrintQuality.DRAFT
PrintQuality.NORMAL
PrintQuality.HIGH

Attribute classes with a finite number of values extend the EnumSyntax class which provides a number of convenience methods to set up these enumerations in a typesafe manner. You don't need to worry about the mechanism when using such an attribute. Simply add the named values to attribute sets:

attributes.add(PrintQuality.HIGH);

Here is how you check the value of an attribute.

if (attributes.get(PrintQuality.class) == PrintQuality.HIGH)
   . . .

Table 7-4 lists the printing attributes. The second column lists the superclass of the attribute class (for example, IntegerSyntax for the Copies attribute), or the set of enumeration values for the attributes with a finite set of values. The last four columns indicate whether the attribute class implements the DocAttribute (DA), PrintJobAttribute (PJA), PrintRequestAttribute (PRA), and PrintServiceAttribute (PSA) interfaces.

NOTE

graphics/note.gif
 

As you can see, there are lots of attributes, many of which are quite specialized. The source for most of the attributes is the Internet Printing Protocol 1.1 (RFC 2911).

This concludes our discussion on printing. You now know how to print 2D graphics and other document types, how to enumerate printers and stream print services, and how to set and retrieve attributes. Next, we will turn to two important user interface issues, the clipboard and support for the drag-and-drop mechanism.

NOTE

graphics/note.gif
 

SDK 1.3 introduced the JobAttributes and PageAttributes classes, whose purpose is similar to the printing attributes covered in this section. Unless you need to specifically support SDK 1.3, you should instead use the more robust SDK 1.4 print service mechanism.

 

Table 7-4. Printing Attributes
Attribute Superclass orenumeration constants DA PJA PRA PSA
Chromaticity MONOCHROME, COLOR x x x  
ColorSupported SUPPORTED, NOT_SUPPORTED       x
Compression COMPRESS, DEFLATE, GZIP, NONE x      
Copies IntegerSyntax   x x  
DateTimeAtCompleted DateTimeSyntax   x    
DateTimeAtCreation DateTimeSyntax   x    
DateTimeAtProcessing DateTimeSyntax   x    
Destination URISyntax   x x  
DocumentName TextSyntax x      
Fidelity FIDELITY_TRUE, FIDELITY_FALSE   x x  
Finishings NONE, STAPLE, EDGE_STITCH, BIND, SADDLE_STITCH, COVER, . . . x x x  
JobHoldUntil DateTimeSyntax   x x  
JobImpressions IntegerSyntax   x x  
JobImpressionsCompleted IntegerSyntax   x    
JobKOctets IntegerSyntax   x x  
JobKOctetsProcessed IntegerSyntax   x    
JobMediaSheets IntegerSyntax   x x  
JobMediaSheetsCompleted IntegerSyntax   x    
JobMessageFromOperator TextSyntax   x    
JobName TextSyntax   x x  
JobOriginatingUserName TextSyntax   x    
JobPriority IntegerSyntax   x x  
JobSheets STANDARD, NONE   x x  
JobState ABORTED, CANCELED, COMPLETED, PENDING, PENDING_HELD, PROCESSING, PROCESSING_STOPPED   x    
JobStateReason ABORTED_BY_SYSTEM, DOCUMENT_FORMAT_ERROR, many others        
JobStateReasons HashSet   x    
MediaName ISO_A4_WHITE, ISO_A4_TRANSPARENT, NA_LETTER_WHITE, NA_LETTER_TRANSPARENT x x x  
MediaSize ISO.A0 - ISO.A10, ISO.B0 - ISO.B10, ISO.C0 - ISO.C10, NA.LETTER, NA.LEGAL, various other paper and envelope sizes        
MediaSizeName ISO_A0 - ISO_A10, ISO_B0 - ISO_B10, ISO_C0 - ISO_C10, NA_LETTER, NA_LEGAL, various other paper and envelope size names x x x  
MediaTray TOP, MIDDLE, BOTTOM, SIDE, ENVELOPE, LARGE_CAPACITY, MAIN, MANUAL, x x x  
MultipleDocumentHandling SINGLE_DOCUMENT, SINGLE_DOCUMENT_NEW_SHEET, SEPARATE_DOCUMENTS_COLLATED_COPIES, SEPARATE_DOCUMENTS_UNCOLLATED_COPIES   x x  
NumberOfDocuments IntegerSyntax   x    
NumberOfInterveningJobs IntegerSyntax   x    
NumberUp IntegerSyntax x x x  
OrientationRequested PORTRAIT, LANDSCAPE, REVERSE_PORTRAIT, REVERSE_LANDSCAPE x x x  
OutputDeviceAssigned TextSyntax   x    
PageRanges SetOfInteger x x x  
PagesPerMinute IntegerSyntax       x
PagesPerMinuteColor IntegerSyntax       x
PDLOverrideSupported ATTEMPTED, NOT_ATTEMPTED       x
PresentationDirection TORIGHT_TOBOTTOM, TORIGHT_TOTOP, TOBOTTOM_TORIGHT, TOBOTTOM_TOLEFT, TOLEFT_TOBOTTOM, TOLEFT_TOTOP, TOTOP_TORIGHT, TOTOP_TOLEFT   x x  
PrinterInfo TextSyntax       x
PrinterIsAcceptingJobs ACCEPTING_JOBS, NOT_ACCEPTING_JOBS       x
PrinterLocation TextSyntax       x
PrinterMakeAndModel TextSyntax       x
PrinterMessageFromOperator TextSyntax       x
PrinterMoreInfo URISyntax       x
PrinterMoreInfoManufacturer URISyntax       x
PrinterName TextSyntax       x
PrinterResolution ResolutionSyntax x x x  
PrinterState PROCESSING, IDLE, STOPPED, UNKNOWN       x
PrinterStateReason COVER_OPEN, FUSER_OVER_TEMP, MEDIA_JAM, and many others        
PrinterStateReasons HashMap        
PrinterURI URISyntax       x
PrintQuality DRAFT, NORMAL, HIGH x x x  
QueuedJobCount IntegerSyntax       x
ReferenceUriSchemesSupported FILE, FTP, GOPHER, HTTP, HTTPS, NEWS, NNTP, WAIS        
RequestingUserName TextSyntax     x  
Severity ERROR, REPORT, WARNING        
SheetCollate COLLATED, UNCOLLATED x x x  
Sides ONE_SIDED, DUPLEX (=TWO_SIDED_LONG_EDGE), TUMBLE (=TWO_SIDED_SHORT_EDGE) x x x  
javax.print.attribute.Attribute

graphics/api.gif
 

javax.print.attribute.AttributeSet

graphics/api.gif
 

javax.print.PrintService

graphics/api.gif
 

javax.print.DocPrintJob

graphics/api.gif
 

The Clipboard

One of the most useful and convenient user interface mechanisms of graphical user interface environments (such as Windows and the X Window System) is cut and paste. You select some data in one program and cut or copy it to the clipboard. Then, you select another program and paste the clipboard contents into that application. Using the clipboard, you can transfer text, images, or other data from one document to another, or, of course, from one place in a document to another place in the same document. Cut and paste is so natural that most computer users never think about it.

However, in SDK 1.0, there was no support for cut and paste. You could not cut and paste between Java applications. For example, if you have a browser written in the Java programming language, then you could not copy text and images from a web page and transfer them into a word processor based on Java technology. SDK 1.1 implemented a rudimentary clipboard mechanism.

That mechanism has been gradually improved and is now quite usable on a number of platforms.

Even though the clipboard is conceptually simple, implementing clipboard services is actually harder than you might think. Suppose you copy text from a word processor into the clipboard. If you paste that text into another word processor, then you expect that the fonts and formatting will stay intact. That is, the text in the clipboard needs to retain the formatting information. But if you paste the text into a plain text field, then you expect that just the characters are pasted in, without additional formatting codes. To support this flexibility, the data provider can offer the clipboard data in multiple formats, and the data consumer can pick one of them.

The system clipboard implementations of Microsoft Windows, OS/2, and the Macintosh are similar, but, of course, there are slight differences. However, the X Window System clipboard mechanism is much more limited—cutting and pasting of anything but plain text is only sporadically supported. You should consider these limitations when trying out the programs in this section.

NOTE

graphics/note.gif
 

Check out the file jre/lib/flavormap.properties on your platform to get an idea what kinds of objects can be transferred between Java programs and the system clipboard.

Often, programs need to support cut and paste of data types that the system clipboard cannot handle. The data transfer API supports the transfer of arbitrary local object references in the same virtual machine. Between different virtual machines, you can transfer serialized objects and references to remote objects.

Table 7-5 summarizes the data transfer capabilities of the clipboard mechanism.

Table 7-5. Capabilities of the Java data transfer mechanism
Transfer Format
Between a program in Java programming language and a native program Text, images, file lists, … (depending on the host platform)
Between two cooperating programs in the Java programming language Serialized and remote objects
Within one program in the Java programming language Any object

Classes and Interfaces for Data Transfer

Data transfer in the Java technology is implemented in a package called java.awt.datatransfer. Here is an overview of the most important classes and interfaces of that package.

Transferring Text

The best way to get comfortable with the data transfer classes is to start with the simplest situation: transferring text to and from the system clipboard. The idea of the following program is simple. First, get a reference to the system clipboard.

Clipboard clipboard =
   Toolkit.getDefaultToolkit().getSystemClipboard();

For strings to be transferred to the clipboard, they need to be wrapped into StringSelection objects. The constructor takes the text you want to transfer.

String text = . . .
StringSelection selection = new StringSelection(text);

The actual transfer is done by a call to setContents, which takes a StringSelection object and a ClipBoardOwner as parameters. If you are not interested in designating a clipboard owner, set the second parameter to null.

clipboard.setContents(selection, null);

Let us look at the reverse operation, reading a string from the clipboard. Call the getContents method of the clipboard to get a Transferable object.

Transferable contents = clipBoard.getContents(null);

According to the API documentation, the parameter of the getContents call is an Object reference of the requesting object. It is not clear why the clipboard collects this information.

The return value of getContents may be null. That indicates that the clipboard is either empty or that it has no data that the Java platform knows how to retrieve.

The Transferable object can tell you in which flavors the clipboard information is available. We will discuss the details of flavor discovery later. For now, we want only the standard flavor called DataFlavor.stringFlavor. Use the isDataFlavorSupported method to find out whether the flavor that you want is actually available.

Finally, you pass the desired flavor to the getTransferData method. The method call must be enclosed in a try block because the method threatens to throw an UnsupportedFlavorException if the requested flavor is not available, or an IOException if it cannot read the data.

DataFlavor flavor = DataFlavor.stringFlavor;
if (contents.isDataFlavorSupported(flavor))
{
   try
   {
      String text = (String)(contents.getTransferData(flavor);
      do something with text;
   }
   catch(UnsupportedFlavorException exception)
   {
      . . .
   }
   catch(IOException exception)
   {
      . . .
   }
}

Example 7-16 is a program that demonstrates cutting and pasting between a Java application and the system clipboard. Figure 7-45 shows a screen shot. If you select an area of text in the text area and click on Copy, then the selected text is copied to the system clipboard. As Figure 7-46 shows, the copied text does indeed get stored on the system clipboard. When you subsequently click on the Paste button, the contents of the clipboard (which may come from a native program) are pasted at the cursor position.

Figure 7-45. The TextTransferTest program

graphics/07fig45.gif
 

Figure 7-46. The Windows clipboard viewer after a copy

graphics/07fig46.gif
 

Example 7-16 TextTransferTest.java
  1. import java.awt.*;
  2. import java.awt.datatransfer.*;
  3. import java.awt.event.*;
  4. import java.io.*;
  5. import javax.swing.*;
  6.
  7. /**
  8.    This program demonstrates the transfer of text
  9.    between a Java application and the system clipboard.
 10. */
 11. public class TextTransferTest
 12. {
 13.    public static void main(String[] args)
 14.    {
 15.       JFrame frame = new TextTransferFrame();
 16.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 17.       frame.show();
 18.    }
 19. }
 20.
 21. /**
 22.    This frame has a text area and buttons for copying and
 23.    pasting text.
 24. */
 25. class TextTransferFrame extends JFrame
 26. {
 27.    public TextTransferFrame()
 28.    {
 29.       setTitle("TextTransferTest");
 30.       setSize(WIDTH, HEIGHT);
 31.
 32.       Container contentPane = getContentPane();
 33.
 34.       textArea = new JTextArea();
 35.       contentPane.add(new JScrollPane(textArea),
 36.          BorderLayout.CENTER);
 37.       JPanel panel = new JPanel();
 38.
 39.       JButton copyButton = new JButton("Copy");
 40.       panel.add(copyButton);
 41.       copyButton.addActionListener(new
 42.          ActionListener()
 43.          {
 44.             public void actionPerformed(ActionEvent event)
 45.             {
 46.                copy();
 47.             }
 48.          });
 49.
 50.       JButton pasteButton = new JButton("Paste");
 51.       panel.add(pasteButton);
 52.       pasteButton.addActionListener(new
 53.          ActionListener()
 54.          {
 55.             public void actionPerformed(ActionEvent event)
 56.             {
 57.                paste();
 58.             }
 59.          });
 60.
 61.       contentPane.add(panel, BorderLayout.SOUTH);
 62.    }
 63.
 64.    /**
 65.       Copies the selected text to the system clipboard.
 66.    */
 67.    private void copy()
 68.    {
 69.       Clipboard clipboard
 70.          = Toolkit.getDefaultToolkit().getSystemClipboard();
 71.       String text = textArea.getSelectedText();
 72.       if (text == null) text = textArea.getText();
 73.       StringSelection selection = new StringSelection(text);
 74.       clipboard.setContents(selection, null);
 75.    }
 76.
 77.    /**
 78.       Pastes the text from the system clipboard into the
 79.       text area.
 80.    */
 81.    private void paste()
 82.    {
 83.        Clipboard clipboard
 84.           = Toolkit.getDefaultToolkit().getSystemClipboard();
 85.       Transferable contents = clipboard.getContents(this);
 86.       if (contents == null) return;
 87.       DataFlavor flavor = DataFlavor.stringFlavor;
 88.       if (contents.isDataFlavorSupported(flavor))
 89.       {
 90.          try
 91.          {
 92.             String text
 93.                = (String)(contents.getTransferData(flavor));
 94.             textArea.replaceSelection(text);
 95.          }
 96.          catch(UnsupportedFlavorException exception)
 97.          {
 98.             JOptionPane.showMessageDialog(this, exception);
 99.          }
100.          catch(IOException exception)
101.          {
102.             JOptionPane.showMessageDialog(this, exception);
103.           }
104.       }
105.    }
106.
107.    private JTextArea textArea;
108.
109.    private static final int WIDTH = 300;
110.    private static final int HEIGHT = 300;
111. }
java.awt.Toolkit

graphics/api.gif
 

java.awt.datatransfer.Clipboard

graphics/api.gif
 

java.awt.datatransfer.ClipboardOwner

graphics/api.gif
 

java.awt.datatransfer.Transferable

graphics/api.gif
 

The Transferable Interface and Data Flavors

The clipboard holds an object that implements the Transferable interface. You can find out all data flavors that a transferable object supports:

DataFlavor[] flavors = transferable.getTransferDataFlavors()

A DataFlavor is defined by two characteristics:

In addition, every data flavor has a human-readable name (such as "GIF Image").

The representation class can be specified with a class parameter in the MIME type, for example,

image/gif;class=java.awt.Image

NOTE

graphics/note.gif
 

This is just an example to show the syntax. There is no standard data flavor for transferring GIF image data.

If no class parameter is given, then the representation class is InputStream.

Sun Microsystems defines three MIME types:

application/x-java-jvm-local-objectref
application/x-java-serialized-object
application/x-java-remote-object

for transferring local, serialized, and remote Java objects.

NOTE

graphics/note.gif
 

The x- prefix indicates that this is an experimental name, not one that is sanctioned by IANA, the organization that assigns standard MIME type names.

For example, the standard stringFlavor data flavor is described by the MIME type

application/x-java-serialized-object;class=java.lang.String
java.awt.datatransfer.DataFlavor

graphics/api.gif
 

java.awt.datatransfer.Transferable

graphics/api.gif
 

Building an Image Transferable

Objects that you want to transfer via the clipboard must implement the Transferable interface. The StringSelection class is currently the only public class in the Java standard library that implements the Transferable interface. In this section, you will see how to transfer images into the clipboard. Since the SDK does not supply a class for image transfer, you must implement it yourself.

The class is completely trivial. It simply reports that the only available data format is DataFlavor.imageFlavor, and it holds an image object.

class ImageSelection implements Transferable
{
   public ImageSelection(Image image)
   {
      theImage = image;
   }

   public DataFlavor[] getTransferDataFlavors()
   {
      return new DataFlavor[] { DataFlavor.imageFlavor };
   }

   public boolean isDataFlavorSupported(DataFlavor flavor)
   {
      return flavor.equals(DataFlavor.imageFlavor);
   }

   public Object getTransferData(DataFlavor flavor)
      throws UnsupportedFlavorException
   {
      if(flavor.equals(DataFlavor.imageFlavor))
      {
         return theImage;
      }
      else
      {
         throw new UnsupportedFlavorException(flavor);
      }
   }

   private Image theImage;
}

NOTE

graphics/note.gif
 

The SDK supplies the DataFlavor.imageFlavor constant and does all the heavy lifting to convert between Java images and native clipboard images. But, curiously, it does not supply the wrapper class that is necessary to place images into the clipboard.

The program of Example 7-17 demonstrates the transfer of images between a Java application and the system clipboard. When the program starts, it generates a Mandelbrot image. Click the Copy button to copy the image to the clipboard and then paste it into another application. (See Figure 7-47). From another application, copy an image into the system clipboard. Then click the Paste button and see the image being pasted into the example program. (See Figure 7-48).

Figure 7-47. Copying from a Java program to a native program

graphics/07fig47.gif
 

Figure 7-48. Copying from a native program to a Java program

graphics/07fig48.gif
 

The program is a straightforward modification of the text transfer program. The data flavor is now DataFlavor.imageFlavor, and we use the ImageSelection class to transfer an image to the system clipboard.

Example 7-17 ImageTransferTest.java
  1. import java.io.*;
  2. import java.awt.*;
  3. import java.awt.datatransfer.*;
  4. import java.awt.event.*;
  5. import java.awt.image.*;
  6. import javax.swing.*;
  7.
  8. /**
  9.    This program demonstrates the transfer of images
 10.    between a Java application and the system clipboard.
 11. */
 12. public class ImageTransferTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new ImageTransferFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame has an image label and buttons for copying and
 24.    pasting text.
 25. */
 26. class ImageTransferFrame extends JFrame
 27. {
 28.    public ImageTransferFrame()
 29.    {
 30.       setTitle("ImageTransferTest");
 31.       setSize(WIDTH, HEIGHT);
 32.
 33.       Container contentPane = getContentPane();
 34.
 35.       label = new JLabel();
 36.       image = makeMandelbrot(WIDTH, HEIGHT);
 37.       label.setIcon(new ImageIcon(image));
 38.       contentPane.add(new JScrollPane(label),
 39.          BorderLayout.CENTER);
 40.       JPanel panel = new JPanel();
 41.
 42.       JButton copyButton = new JButton("Copy");
 43.       panel.add(copyButton);
 44.       copyButton.addActionListener(new
 45.          ActionListener()
 46.          {
 47.             public void actionPerformed(ActionEvent event)
 48.             {
 49.                copy();
 50.             }
 51.          });
 52.
 53.       JButton pasteButton = new JButton("Paste");
 54.       panel.add(pasteButton);
 55.       pasteButton.addActionListener(new
 56.          ActionListener()
 57.          {
 58.             public void actionPerformed(ActionEvent event)
 59.             {
 60.                paste();
 61.             }
 62.          });
 63.
 64.       contentPane.add(panel, BorderLayout.SOUTH);
 65.    }
 66.
 67.    /**
 68.       Copies the current image to the system clipboard.
 69.    */
 70.    private void copy()
 71.    {
 72.       Clipboard clipboard
 73.          = Toolkit.getDefaultToolkit().getSystemClipboard();
 74.       ImageSelection selection = new ImageSelection(image);
 75.       clipboard.setContents(selection, null);
 76.    }
 77.
 78.    /**
 79.       Pastes the image from the system clipboard into the
 80.       image label.
 81.    */
 82.    private void paste()
 83.    {
 84.       Clipboard clipboard
 85.          = Toolkit.getDefaultToolkit().getSystemClipboard();
 86.       Transferable contents = clipboard.getContents(null);
 87.       if (contents == null) return;
 88.       DataFlavor flavor = DataFlavor.imageFlavor;
 89.       if (contents.isDataFlavorSupported(flavor))
 90.       {
 91.          try
 92.          {
 93.             image = (Image)(contents.getTransferData(flavor));
 94.             label.setIcon(new ImageIcon(image));
 95.          }
 96.          catch(UnsupportedFlavorException exception)
 97.          {
 98.             JOptionPane.showMessageDialog(this, exception);
 99.          }
100.          catch(IOException exception)
101.          {
102.             JOptionPane.showMessageDialog(this, exception);
103.          }
104.        }
105.    }
106.
107.    /**
108.       Makes the Mandelbrot image.
109.       @param width the width
110.       @parah height the height
111.       @return the image
112.    */
113.    public BufferedImage makeMandelbrot(int width, int height)
114.    {
115.       BufferedImage image = new BufferedImage(width, height,
116.          BufferedImage.TYPE_INT_ARGB);
117.       WritableRaster raster = image.getRaster();
118.       ColorModel model = image.getColorModel();
119.
120.       Color fractalColor = Color.red;
121.       int argb = fractalColor.getRGB();
122.       Object colorData = model.getDataElements(argb, null);
123.
124.       for (int i = 0; i < width; i++)
125.          for (int j = 0; j < height; j++)
126.          {
127.             double a = XMIN + i * (XMAX - XMIN) / width;
128.             double b = YMIN + j * (YMAX - YMIN) / height;
129.             if (!escapesToInfinity(a, b))
130.                raster.setDataElements(i, j, colorData);
131.          }
132.       return image;
133.     }
134.
135.    private boolean escapesToInfinity(double a, double b)
136.    {
137.       double x = 0. 0;
138.       double y = 0. 0;
139.       int iterations = 0;
140.       do
141.       {
142.          double xnew = x * x - y * y + a;
143.          double ynew = 2 * x * y + b;
144.          x = xnew;
145.          y = ynew;
146.          iterations++;
147.          if (iterations == MAX_ITERATIONS) return false;
148.       }
149.       while (x <= 2 && y <= 2);
150.       return true;
151.    }
152.
153.    private JLabel label;
154.    private Image image;
155.
156.    private static final double XMIN = -2;
157.    private static final double XMAX = 2;
158.    private static final double YMIN = -2;
159.    private static final double YMAX = 2;
160.    private static final int MAX_ITERATIONS = 16;
161.
162.    private static final int WIDTH = 300;
163.    private static final int HEIGHT = 300;
164. }
165.
166. /**
167.    This class is a wrapper for the data transfer of image
168.    objects.
169. */
170. class ImageSelection implements Transferable
171. {
172.    /**
173.       Constructs the selection.
174.       @param image an image
175.    */
176.    public ImageSelection(Image image)
177.    {
178.       theImage = image;
179.    }
180.
181.    public DataFlavor[] getTransferDataFlavors()
182.    {
183.       return new DataFlavor[] { DataFlavor.imageFlavor };
184.    }
185.
186.    public boolean isDataFlavorSupported(DataFlavor flavor)
187.    {
188.       return flavor.equals(DataFlavor.imageFlavor);
189.    }
190.
191.    public Object getTransferData(DataFlavor flavor)
192.       throws UnsupportedFlavorException
193.    {
194.       if(flavor.equals(DataFlavor.imageFlavor))
195.       {
196.          return theImage;
197.       }
198.       else
199.       {
200.          throw new UnsupportedFlavorException(flavor);
201.       }
202.    }
203.
204.    private Image theImage;
205. }

Using a Local Clipboard to Transfer Object References

Suppose you want to copy and paste a data type that isn't one of the data types supported by the system clipboard. For example, in a drawing program, you may want to allow your users to copy and paste arbitrary shapes.

The program in Example 7-18 demonstrates this capability. As you can see in Figure 7-49, the program displays two panels. By moving the rectangle "grabbers" in the left panel, you can change the shape of a cubic curve. The panel on the right side can display an arbitrary shape.

Figure 7-49. Transferring Local Objects

graphics/07fig49.gif
 

When you click on the Copy button, the current cubic curve shape is copied. Click on Paste, and the Shape object in the clipboard is displayed in the panel on the right hand side. You can see that the shape is held in a clipboard by copying a curve and then modifying the curve before pasting. The copied shape, and not the current shape of the curve, is pasted into the right side panel.

To transfer an arbitrary Java object reference within the same JVM, you use the MIME type

application/x-java-jvm-local-objectref;class=className

However, the SDK doesn't include a Transferable wrapper for this type. You can find the code for the wrapper in the example program. It is entirely analogous to the ImageSelection wrapper of the preceding section.

An object reference is only meaningful within a single virtual machine. For that reason, you cannot copy the shape object to the system clipboard. Instead, this program uses a local clipboard:

Clipboard clipboard = new Clipboard("local");

The construction parameter is the clipboard name.

However, using a local clipboard has one major disadvantage. You need to synchronize the local and the system clipboard, so that users don't get confused between the two. Currently, the Java platform doesn't do that synchronization for you.

Example 7-18 LocalTransferTest.java
  1. import java.awt.*;
  2. import java.awt.datatransfer.*;
  3. import java.awt.event.*;
  4. import java.awt.geom.*;
  5. import java.io.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    This program demonstrates the transfer of object references
 11.    within the same virtual machine.
 12. */
 13. public class LocalTransferTest
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new LocalTransferFrame();
 18.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame contains a panel to edit a cubic curve, a
 25.    panel that can display an arbitrary shape, and copy and
 26.    paste buttons.
 27. */
 28. class LocalTransferFrame extends JFrame
 29. {
 30.    public LocalTransferFrame()
 31.    {
 32.       setTitle("LocalTransferTest");
 33.       setSize(WIDTH, HEIGHT);
 34.
 35.       Container contentPane = getContentPane();
 36.
 37.       curvePanel = new CubicCurvePanel();
 38.       curvePanel.setPreferredSize(new Dimension(WIDTH / 2,
 39.          HEIGHT));
 40.       shapePanel = new ShapePanel();
 41.
 42.       contentPane.add(new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
 43.          curvePanel, shapePanel), BorderLayout.CENTER);
 44.       JPanel panel = new JPanel();
 45.
 46.       JButton copyButton = new JButton("Copy");
 47.       panel.add(copyButton);
 48.       copyButton.addActionListener(new
 49.          ActionListener()
 50.          {
 51.             public void actionPerformed(ActionEvent event)
 52.             {
 53.                copy();
 54.             }
 55.          });
 56.
 57.       JButton pasteButton = new JButton("Paste");
 58.       panel.add(pasteButton);
 59.       pasteButton.addActionListener(new
 60. .        ActionListener()
 61.          {
 62.             public void actionPerformed(ActionEvent event)
 63.             {
 64.                paste();
 65.             }
 66.          });
 67.
 68.       contentPane.add(panel, BorderLayout.SOUTH);
 69.    }
 70.
 71.    /**
 72.       Copies the current cubic curve to the local clipboard.
 73.    */
 74.    private void copy()
 75.    {
 76.       LocalSelection selection = new LocalSelection(
 77.          curvePanel.getShape());
 78.       clipboard.setContents(selection, null);
 79.    }
 80.
 81.    /**
 82.       Pastes the shape from the local clipboard into the
 83.       shape panel.
 84.    */
 85.    private void paste()
 86.    {
 87.       Transferable contents = clipboard.getContents(null);
 88.       if (contents == null) return;
 89.       try
 90.       {
 91.          DataFlavor flavor = new DataFlavor(
 92. "application/x-java-jvm-local-objectref;class=java.awt.Shape");
 93.          if (contents.isDataFlavorSupported(flavor))
 94.             shapePanel.setShape(
 95.                (Shape)contents.getTransferData(flavor));
 96.       }
 97.       catch(ClassNotFoundException exception)
 98.       {
 99.          JOptionPane.showMessageDialog(this, exception);
100. .     }
101.       catch(UnsupportedFlavorException exception)
102.       {
103.          JOptionPane.showMessageDialog(this, exception);
104.       }
105.       catch(IOException exception)
106.       {
107.          JOptionPane.showMessageDialog(this, exception);
108.       }
109.    }
110.
111.    private CubicCurvePanel curvePanel;
112.    private ShapePanel shapePanel;
113.    private Clipboard clipboard = new Clipboard("local");
114.
115.    private static final int WIDTH = 30. 0. ;
116.    private static final int HEIGHT = 30. 0. ;
117. }
118.
119.
120. /**
121.    This panel draws a shape and allows the user to
122.    move the points that define it.
123. */
124. class CubicCurvePanel extends JPanel
125. {
126.    public CubicCurvePanel()
127.    {
128.       addMouseListener(new
129.          MouseAdapter()
130.          {
131.             public void mousePressed(MouseEvent event)
132.             {
133.                for (int i = 0. ; i < p.length; i++)
134.                {
135.                   double x = p[i].getX() - SIZE / 2;
136.                   double y = p[i].getY() - SIZE / 2;
137.                   Rectangle2D r
138.                      = new Rectangle2D.Double(x, y, SIZE, SIZE);
139.                   if (r.contains(event.getPoint()))
140. .                 {
141.                      current = i;
142.                      return;
143.                   }
144.                }
145.             }
146.
147.             public void mouseReleased(MouseEvent event)
148.             {
149.                current = -1;
150.             }
151.           });
152.
153.        addMouseMotionListener(new
154.           MouseMotionAdapter()
155.           {
156.              public void mouseDragged(MouseEvent event)
157.              {
158.                if (current == -1) return;
159.                p[current] = event.getPoint();
160. .              repaint();
161.             }
162.          });
163.
164.       current = -1;
165.    }
166.
167.    public void paintComponent(Graphics g)
168.    {
169.       super.paintComponent(g);
170.       Graphics2D g2 = (Graphics2D)g;
171.       for (int i = 0. ; i < p.length; i++)
172.       {
173.          double x = p[i].getX() - SIZE / 2;
174.          double y = p[i].getY() - SIZE / 2;
175.          g2.fill(new Rectangle2D.Double(x, y, SIZE, SIZE));
176.       }
177.
178.       g2.draw(getShape());
179.    }
180.
181.    /**
182.       Gets the current cubic curve.
183.       @return the curve shape
184.    */
185.    public Shape getShape()
186.    {
187.       return new CubicCurve2D.Double(p[0. ].getX(), p[0. ].getY(),
188.          p[1].getX(), p[1].getY(), p[2].getX(), p[2].getY(),
189.          p[3].getX(), p[3].getY());
190.    }
191.
192.    private Point2D[] p =
193.    {
194.       new Point2D.Double(10. , 10. ),
195.       new Point2D.Double(10. , 10. 0. ),
196.       new Point2D.Double(10. 0. , 10. ),
197.       new Point2D.Double(10. 0. , 20. 0. )
198.    };
199.    private static int SIZE = 10. ;
200.    private int current;
201. }
202.
203. /**
204.    This panel displays an arbitrary shape.
205. */
206. class ShapePanel extends JPanel
207. {
208.    /**
209.       Set the shape to be displayed in this panel.
210.       @param aShape any shape
211.    */
212.    public void setShape(Shape aShape)
213.    {
214.       shape = aShape;
215.       repaint();
216.    }
217.
218.    public void paintComponent(Graphics g)
219.    {
220.       super.paintComponent(g);
221.       Graphics2D g2 = (Graphics2D)g;
222.       if (shape != null) g2.draw(shape);
223.    }
224.
225.    private Shape shape;
226. }
227.
228. /**
229.    This class is a wrapper for the data transfer of
230.    object references that are transferred within the same
231.    virtual machine.
232. */
233. class LocalSelection implements Transferable
234. {
235.    /**
236.       Constructs the selection.
237.       @param o any object
238.    */
239.    LocalSelection(Object o)
240.    {
241.       obj = o;
242.    }
243.
244.    public DataFlavor[] getTransferDataFlavors()
245.    {
246.       DataFlavor[] flavors = new DataFlavor[1];
247.       Class type = obj.getClass();
248.       String mimeType
249.          = "application/x-java-jvm-local-objectref;class="
250.          + type.getName();
251.       try
252.       {
253.          flavors[0. ] = new DataFlavor(mimeType);
254.          return flavors;
255.       }
256.       catch (ClassNotFoundException exception)
257.       {
258.          return new DataFlavor[0. ];
259.       }
260.    }
261.
262.    public boolean isDataFlavorSupported(DataFlavor flavor)
263.    {
264.       return "application".equals(flavor.getPrimaryType())
265.          && "x-java-jvm-local-objectref".equals(
266.             flavor.getSubType())
267.          && flavor.getRepresentationClass().isAssignableFrom(
268.             obj.getClass());
269.    }
270.
271.    public Object getTransferData(DataFlavor flavor)
272.       throws UnsupportedFlavorException
273.    {
274.       if (! isDataFlavorSupported(flavor))
275.          throw new UnsupportedFlavorException(flavor);
276.
277.       return obj;
278.    }
279.
280.    private Object obj;
281. }
java.awt.datatransfer.Clipboard

graphics/api.gif
 

Transferring Java Objects via the System Clipboard

Suppose you want to copy and paste objects from one Java application to another. Then you cannot use local clipboards. Fortunately, you can place serialized Java objects onto the system clipboard.

The program in Example 7-19 demonstrates this capability. The program shows a color chooser. The Copy button copies the current color to the system clipboard as a serialized Color object. The Paste button checks whether the system clipboard contains a serialized Color object. If so, it fetches the color and sets it as the current choice of the color chooser.

You can transfer the serialized object between two Java applications (see Figure 7-50). Run two copies of the SerialTransferTest program. Click on "Copy" in the first program, then on "Paste" in the second program. The Color object is transferred from one virtual machine to the other.

Figure 7-50. Data is copied between two instances of a Java application

graphics/07fig50.gif
 

To enable the data transfer, the Java platform places binary data on the system clipboard that contain the serialized object. Another Java program—not necessarily of the same type as the one that generated the clipboard data—can retrieve the clipboard data and deserialize the object.

Of course, a non-Java application will not know what to do with the clipboard data. For that reason, the example program offers the clipboard data in a second flavor, as text. The text is simply the result of the toString method, applied to the transferred object. To see the second flavor, run the program, click on a color, and then select the "Paste" command in your text editor. A string such as

java.awt.Color[r=255,g=51,b=51]

will be inserted into your document.

Essentially no additional programming is required to transfer a serializable object. You use the MIME type

application/x-java-serialized-object;class=className

As before, you have to build your own transfer wrapper—see the example code for details.

Example 7-19 SerialTransferTest.java
  1. import java.io.*;
  2. import java.awt.*;
  3. import java.awt.datatransfer.*;
  4. import java.awt.event.*;
  5. import java.awt.image.*;
  6. import javax.swing.*;
  7.
  8. /**
  9.    This program demonstrates the transfer of serialized objects
 10.    between virtual machines.
 11. */
 12. public class SerialTransferTest
 13. {
 14.    public static void main(String[] args)
 15.    {
 16.       JFrame frame = new SerialTransferFrame();
 17.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 18.       frame.show();
 19.    }
 20. }
 21.
 22. /**
 23.    This frame contains a color chooser, and copy and
 24.    paste buttons.
 25. */
 26. class SerialTransferFrame extends JFrame
 27. {
 28.    public SerialTransferFrame()
 29.    {
 30.       setTitle("SerialTransferTest");
 31.
 32.       Container contentPane = getContentPane();
 33.
 34.       chooser = new JColorChooser();
 35.       contentPane.add(chooser, BorderLayout.CENTER);
 36.       JPanel panel = new JPanel();
 37.
 38.       JButton copyButton = new JButton("Copy");
 39.       panel.add(copyButton);
 40.       copyButton.addActionListener(new
 41.          ActionListener()
 42.          {
 43.             public void actionPerformed(ActionEvent event)
 44.             {
 45.                copy();
 46.             }
 47.          });
 48.
 49.       JButton pasteButton = new JButton("Paste");
 50.       panel.add(pasteButton);
 51.       pasteButton.addActionListener(new
 52.          ActionListener()
 53.          {
 54.             public void actionPerformed(ActionEvent event)
 55.             {
 56.                paste();
 57.             }
 58.          });
 59.
 60.       contentPane.add(panel, BorderLayout.SOUTH);
 61.       pack();
 62.    }
 63.
 64.    /**
 65.       Copies the chooser's color into the system clipboard.
 66.    */
 67.    private void copy()
 68.    {
 69.       Clipboard clipboard
 70.          = Toolkit.getDefaultToolkit().getSystemClipboard();
 71.       Color color = chooser.getColor();
 72.       SerialSelection selection = new SerialSelection(color);
 73.       clipboard.setContents(selection, null);
 74.    }
 75.
 76.    /**
 77.       Pastes the color from the system clipboard into the
 78.       chooser.
 79.    */
 80.    private void paste()
 81.    {
 82.       Clipboard clipboard
 83.           = Toolkit.getDefaultToolkit().getSystemClipboard();
 84.       Transferable contents = clipboard.getContents(null);
 85.       if (contents == null) return;
 86.       try
 87.       {
 88.          DataFlavor flavor = new DataFlavor(
 89. "application/x-java-serialized-object;class=java.awt.Color");
 90.          if (contents.isDataFlavorSupported(flavor))
 91.          {
 92.             Color color
 93.                = (Color)contents.getTransferData(flavor);
 94.             chooser.setColor(color);
 95.          }
 96.       }
 97.       catch(ClassNotFoundException exception)
 98.       {
 99.          JOptionPane.showMessageDialog(this, exception);
100.       }
101.       catch(UnsupportedFlavorException exception)
102.       {
103.          JOptionPane.showMessageDialog(this, exception);
104.       }
105.       catch(IOException exception)
106.       {
107.          JOptionPane.showMessageDialog(this, exception);
108.       }
109.    }
110.
111.    private JColorChooser chooser;
112. }
113.
114. /**
115.    This class is a wrapper for the data transfer of
116.    serialized objects.
117. */
118. class SerialSelection implements Transferable
119. {
120.    /**
121.       Constructs the selection.
122.       @param o any serializable object
123.    */
124.    SerialSelection(Serializable o)
125.    {
126.       obj = o;
127.    }
128.
129.    public DataFlavor[] getTransferDataFlavors()
130.    {
131.       DataFlavor[] flavors = new DataFlavor[2];
132.       Class type = obj.getClass();
133.       String mimeType
134.          = "application/x-java-serialized-object;class="
135.          + type.getName();
136.       try
137.       {
138.          flavors[0] = new DataFlavor(mimeType);
139.          flavors[1] = DataFlavor.stringFlavor;
140.          return flavors;
141.       }
142.       catch (ClassNotFoundException exception)
143.       {
144.          return new DataFlavor[0];
145.       }
146.    }
147.
148.    public boolean isDataFlavorSupported(DataFlavor flavor)
149.    {
150.       return
151.          DataFlavor.stringFlavor.equals(flavor)
152.          || "application".equals(flavor.getPrimaryType())
153.          && "x-java-serialized-object".equals(
154.             flavor.getSubType())
155.          && flavor.getRepresentationClass().isAssignableFrom(
156.             obj.getClass());
157.    }
158.
159.    public Object getTransferData(DataFlavor flavor)
160.       throws UnsupportedFlavorException
161.    {
162.       if (!isDataFlavorSupported(flavor))
163.          throw new UnsupportedFlavorException(flavor);
164.
165.       if (DataFlavor.stringFlavor.equals(flavor))
166.          return obj.toString();
167.
168.       return obj;
169.    }
170.
171.    private Serializable obj;
172. }

Drag and Drop

When you use cut and paste to transmit information between two programs, the clipboard acts as an intermediary. The drag and drop metaphor cuts out the middleman and lets two programs communicate directly. The Java 2 platform offers basic support for drag and drop. You can carry out drag and drop operations between Java applications and native applications. This section shows you how to write a Java application that is a drop target, and an application that is a drag source.

Before going deeper into the Java platform support for drag and drop, let us have a quick look at the drag and drop user interface. We'll use the Windows Explorer and WordPad programs as examples—on another platform, you can experiment with locally available programs with drag and drop capabilities.

You initiate a drag operation with a gesture inside a drag source—usually, by first selecting one or more elements and then dragging the selection away from its initial location (see Figure 7-51).

Figure 7-51. Initiating a drag operation

graphics/07fig51.gif

When you release the mouse button over a drop target that accepts the drop operation, then the drop target queries the drag source for information about the dropped elements, and it initiates some operation. For example, if you drop a file icon from Windows Explorer to WordPad, then WordPad opens the file. However, if you drag a file icon on top of a directory icon in Windows Explorer, then it moves the file into that directory.

If you hold down the SHIFT or CTRL key while dragging, then the type of the drop action changes from a move action to a copy action, and a copy of the file is placed into the directory. If you hold down both SHIFT and CTRL keys, then a link to the file is placed into the directory. (Other platforms may use other keyboard combinations for these operations.)

Thus, there are three types of drop actions with different gestures:

The intention of the link action is to establish a reference to the dropped element. Such links typically require support from the host operating system (such as symbolic links for files, or object linking for document components) and don't usually make a lot of sense in cross-platform programs. In this section, we'll focus on using drag and drop for copying and moving.

Not all programs are sensitive to the drop action types. For example, if you drop a file onto WordPad, it ignores the action type and always opens the file.

There is usually some visual feedback for the drag operation. Minimally, the cursor shape will change. As the cursor moves over possible drop targets, the cursor shape indicates whether the drop is possible or not. If a drop is possible, the cursor shape also indicates the type of the drop action. Figure 7-52 shows several cursor shapes over drop targets.

Figure 7-52. Cursor shapes over drop targets

graphics/07fig52.gif
 

You can also drag other elements besides file icons. For example, you can select text in WordPad and drag it. Try dropping text fragments into willing drop targets and see how they react.

NOTE

graphics/note.gif
 

This experiment shows a disadvantage of drag and drop as a user interface mechanism. It can be difficult for users to anticipate what you can drag, where you can drop it, and what happens when you do. Because the default "move" action can remove the original, many users are understandably cautious about experimenting with drag and drop.

Drop Targets

In this section, we will construct a simple Java application that is a drop target. The example program does nothing useful; it simply demonstrates how you can detect that a user would like to initiate a drop, how to accept the drop, and how to analyze the data that is being dropped.

You can designate any AWT component to be a drop target. To do so, you need to construct a DropTarget object and pass the component and a drop target listener to the constructor. The constructor registers the object with the drag and drop system.

DropTarget target = new DropTarget(component, listener);

You can activate or deactivate the target with the setActive method. By default, the target is active.

target.setActive(b);

You can call the setDefaultActions method to set the drop operations that you want to accept by default. The operations are:

DndConstants.ACTION_COPY
DndConstants.ACTION_MOVE
DndConstants.ACTION_COPY_OR_MOVE
DndConstants.ACTION_LINK

By default, all operations are allowed.

Now you need to implement a drop target listener. The DropTargetListener interface has five methods:

void dragEnter(DropTargetDragEvent event)
void dragExit(DropTargetEvent event)
void dragOver(DropTargetDragEvent event)
void dropActionChanged(DropTargetDragEvent event)
void drop(DropTargetDropEvent event)

The dragEnter and dragExit methods are called when the cursor enters or exits the drop target component. In the dragEnter method, you have the chance to set the cursor shape to indicate whether the drop target is willing to accept the drop.

You don't usually worry about the dragExit method. However, if you built up some elaborate mechanism for visual feedback, then you can dispose of it in this method.

The dragOver method is called continuously as the user moves the mouse over the drop target component. You can use it to give detailed visual feedback about the effect of a drop. For example, if the drop target is a tree component, you can highlight the node under the cursor or even open up a subtree if the cursor hovers over a node.

The dropActionChanged method is called if the user changes the action gesture. For example, if the user presses or lifts the SHIFT or CTRL keys while moving the mouse over the drop target component, then this method is called. That gives you a chance to modify the visual feedback and match it to the changed action.

The most important method is the drop method. It is called when the user has committed to a drop by finishing the drop gesture, usually by releasing the mouse button. Note that this method is called whether or not you previously indicated that you would accept the drop.

Look carefully at the parameters of the DropTargetListener methods. Three of them are a DropTargetDragEvent. However, the drop method receives a DropTargetDropEvent, and the dragExit method receives a DropTargetEvent. The DropTargetEvent class is the superclass of the other two event classes. It has only one method, getDropTargetContext, which returns a class with no interesting public methods. Since the purpose of a dragExit method is to do cleanup, you probably won't even look at the parameter.

The DropTargetDragEvent and DropTargetDropEvent classes each have the following methods:

int getDropAction()
Point getLocation()
DataFlavor[] getCurrentDataFlavors()
boolean isDataFlavorSupported(DataFlavor flavor)

You need these methods to test whether to encourage a drag or allow a drop, and how to give visual feedback.

Unfortunately, since the methods are not available in the common superclass, you'll have to implement the test logic twice, once for the drag and then again for the drop.

If you don't want to encourage a drag, you should call the rejectDrag method of the DropTargetDragEvent class in the dragEnter or dropActionChanged method. As a result, the cursor changes to a warning icon. If the user drops an item despite the warning, then you should call the rejectDrop method of the DropTargetDropEvent class.

The getDropAction method returns the drop action that the user intends to carry out. In many drag and drop operations, you don't want the action taken literally. For example, if you move a file icon into WordPad, then you don't want the drag source to delete the file. But you also don't want the drop target to insist that the user hold down a key when dragging. In this situation, the drop target should accept either copy or move actions. In the drop method, call the acceptDrop method of the DropTargetDropEvent with the actual action. If you call

event.acceptDrop(DnDConstants.ACTION_MOVE);
   // drag source deletes dragged items!

then the drag source will delete the dragged items.

TIP

graphics/tip.gif
 

Are you certain that your users understand the distinction between move and copy operations and the role of the SHIFT and CTRL modifiers? Do they realize that the default drag gesture (without a modifier) deletes the dragged items from the source? If not, you should accept a drop as

event.acceptDrop(DnDConstants.ACTION_COPY);

On the other hand, if you really want to make a distinction between move and copy, simply call

event.acceptDrop(event.getDropEvent()).

Here is an overview of a typical drop target listener:

class ADropTargetListener implements DropTargetListener
{
   // convenience methods
   public boolean isDragAcceptable(DropTargetDragEvent event)
   {
      look at drop action and available data flavors
   }

   public boolean isDropAcceptable(DropTargetDropEvent event)
   {
      carry out the same test as in isDragAcceptable
   }

   // listener methods
   public void dragEnter(DropTargetDragEvent event)
   {
      if (!isDragAcceptable(event))
      {
         event.rejectDrag();
         return;
      }
   }

   public void dragExit(DropTargetEvent event)
   {
   }

   public void dragOver(DropTargetDragEvent event)
   {
      // you can provide visual feedback here
   }

   public void dropActionChanged(DropTargetDragEvent event)
   {
      if (!isDragAcceptable(event))
      {
         event.rejectDrag();
         return;
      }
   }

   public void drop(DropTargetDropEvent event)
   {
      if (!isDropAcceptable(event))
      {
         event.rejectDrop();
         return;
      }
      event.acceptDrop(actual action);
      process data from drag source
      event.dropComplete(true);
   }
   . . .
}

Once you accept a drop, you need to analyze the data from the drag source. The getTransferable method of the DropTargetDropEvent class returns a reference to a Transferable object. This is the same interface that is used for copy and paste.

One data type that is more commonly used for drag and drop than for copy and paste is the DataFlavor.javaFileListFlavor. A file list describes a set of file icons that was dropped onto the target. The Transferable object yields an object of type java.util.List whose items are File objects. Here is the code for retrieving the files:

DataFlavor[] flavors = transferable.getTransferDataFlavors();
DataFlavor flavor = flavors[i];
if (flavor.equals(DataFlavor.javaFileListFlavor))
{
   java.util.List fileList
      = (java.util.List)transferable.getTransferData(flavor);
   Iterator iterator = fileList.iterator();
   while (iterator.hasNext())
   {
      File f = (File)iterator.next();
      do something with f;
   }
}

Another flavor that can be dropped is text. You can retrieve the text in various flavors. The most convenient is DataFlavor.stringFlavor. The other flavors have a MIME type of text/plain and a variety of representation classes, including InputStream and [B (byte array).

CAUTION

graphics/caution.gif
 

Earlier versions of the Java platform did not go through the effort of converting dragged text to Unicode and giving you a stringFlavor. Instead, you had to retrieve the text through an InputStream. The text/plain MIME type contains a charset parameter that indicates the character encoding. To compound the inconvenience, those Java platform versions also used character encoding names that were different from the names that the InputStreamReader constructor expects. In particular, you had to convert ascii to ISO-8859-1 and unicode to Unicode.

Under Windows, you ran into additional problems. The end of input was indicated by a null character, and you should not read past it. The Unicode data didn't start with a Unicode byte order marker that the InputStreamReader expects, resulting in a sun.io.MalformedInputException. Thus, programmers had to bypass the InputStreamReader and construct the Unicode characters from pairs of bytes.

Fortunately, these growing pains have been overcome in SDK 1.4.

Depending on the drag source, you may also find data in other formats such as

text/html
text/rtf

If you want to read the data in that format, pick a convenient flavor, for example an input stream, and obtain the data like this:

if (flavor.isMimeTypeEqual("text/html")
   && flavor.getRepresentationClass() == InputStream.class)
{
   String charset = flavor.getParameter("charset");
   InputStreamReader in = new InputStreamReader(
      transferable.getTransferData(flavor), charset);
   read data from in
}

Our sample program does not attempt to do anything useful. It simply lets you drop items onto a text area. When you start dragging over the text area, the drop action is displayed. Once you initiate a drop, the dropped data is displayed. If the data is in text format, the program reads both ascii and unicode encodings.

In our sample program, we will not give any visual feedback of the dragging process beyond the change to a warning cursor that automatically happens when calling the rejectDrag method.

The purpose of this program is simply to give you a drop target for experimentation. Try dropping a selection of file names from Windows Explorer, or a text fragment from WordPad (see Figure 7-53). Also see how a link attempt is rejected. If you press both the SHIFT and CTRL keys, then a warning icon appears when you drag an item over the text area.

Figure 7-53. The DropTargetTest program

graphics/07fig53.gif
 

Example 7-20 shows the complete program.

Example 7-20 DropTargetTest.java
  1. import java.awt.*;
  2. import java.awt.datatransfer.*;
  3. import java.awt.event.*;
  4. import java.awt.dnd.*;
  5. import java.io.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    This is a test class to test drag and drop behavior. Drop
 11.    items into the text area to see the MIME types of the
 12.    drop target.
 13. */
 14. public class DropTargetTest
 15. {
 16.    public static void main(String[] args)
 17.    {
 18.       JFrame frame = new DropTargetFrame();
 19.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 20.       frame.show();
 21.    }
 22. }
 23.
 24. /**
 25.    This frame contains a text area that is a simple drop target.
 26. */
 27. class DropTargetFrame extends JFrame
 28. {
 29.    public DropTargetFrame()
 30.    {
 31.       setTitle("DropTarget");
 32.       setSize(WIDTH, HEIGHT);
 33.
 34.       Container contentPane = getContentPane();
 35.       JTextArea textArea
 36.          = new JTextArea("Drop items into this text area.\n");
 37.
 38.       new DropTarget(textArea,
 39.          new TextDropTargetListener(textArea));
 40.       contentPane.add(new JScrollPane(textArea), "Center");
 41.    }
 42.
 43.    private static final int WIDTH = 300;
 44.    private static final int HEIGHT = 300;
 45. }
 46.
 47. /**
 48.    This listener displays the properties of a dropped object.
 49. */
 50. class TextDropTargetListener implements DropTargetListener
 51. {
 52.    /**
 53.       Constructs a listener.
 54.       @param aTextArea the text area in which to display the
 55.       properties of the dropped object.
 56.    */
 57.    public TextDropTargetListener(JTextArea aTextArea)
 58.    {
 59.       textArea = aTextArea;
 60.    }
 61.
 62.    public void dragEnter(DropTargetDragEvent event)
 63.    {
 64.       int a = event.getDropAction();
 65.       if ((a & DnDConstants.ACTION_COPY) != 0)
 66.          textArea.append("ACTION_COPY\n");
 67.       if ((a & DnDConstants.ACTION_MOVE) != 0)
 68.          textArea.append("ACTION_MOVE\n");
 69.       if ((a & DnDConstants.ACTION_LINK) != 0)
 70.          textArea.append("ACTION_LINK\n");
 71.
 72.       if (!isDragAcceptable(event))
 73.       {
 74.          event.rejectDrag();
 75.          return;
 76.       }
 77.    }
 78.
 79.    public void dragExit(DropTargetEvent event)
 80.    {
 81.    }
 82.
 83.    public void dragOver(DropTargetDragEvent event)
 84.    {
 85.       // you can provide visual feedback here
 86.    }
 87.
 88.    public void dropActionChanged(DropTargetDragEvent event)
 89.    {
 90.       if (!isDragAcceptable(event))
 91.       {
 92.          event.rejectDrag();
 93.          return;
 94.       }
 95.    }
 96.
 97.    public void drop(DropTargetDropEvent event)
 98.    {
 99.       if (!isDropAcceptable(event))
100.       {
101.          event.rejectDrop();
102.          return;
103.       }
104.
105.       event.acceptDrop(DnDConstants.ACTION_COPY);
106.
107.       Transferable transferable = event.getTransferable();
108.
109.       DataFlavor[] flavors
110.          = transferable.getTransferDataFlavors();
111.       for (int i = 0; i < flavors.length; i++)
112.       {
113.          DataFlavor d = flavors[i];
114.          textArea.append("MIME type=" + d.getMimeType() + "\n");
115.
116.          try
117.          {
118.             if (d.equals(DataFlavor.javaFileListFlavor))
119.             {
120.                java.util.List fileList = (java.util.List)
121.                   transferable.getTransferData(d);
122.                Iterator iterator = fileList.iterator();
123.                while (iterator.hasNext())
124.                {
125.                   File f = (File)iterator.next();
126.                   textArea.append(f + "\n");
127.                }
128.             }
129.             else if (d.equals(DataFlavor.stringFlavor))
130.             {
131.                String s = (String)
132.                   transferable.getTransferData(d);
133.                textArea.append(s + "\n");
134.             }
135.          }
136.          catch(Exception e)
137.          {
138.             textArea.append(e + "\n");
139.          }
140.       }
141.       textArea.append("\n");
142.       event.dropComplete(true);
143.    }
144.
145.    public boolean isDragAcceptable(DropTargetDragEvent event)
146.    {
147.       // usually, you check the available data flavors here
148.       // in this program, we accept all flavors
149.       return (event.getDropAction()
150.          & DnDConstants.ACTION_COPY_OR_MOVE) != 0;
151.    }
152.
153.    public boolean isDropAcceptable(DropTargetDropEvent event)
154.    {
155.       // usually, you check the available data flavors here
156.       // in this program, we accept all flavors
157.       return (event.getDropAction()
158.          & DnDConstants.ACTION_COPY_OR_MOVE) != 0;
159.    }
160.
161.    private JTextArea textArea;
162. }
java.awt.dnd.DropTarget

graphics/api.gif
 

java.awt.dnd.DropTargetListener

graphics/api.gif
 

java.awt.dnd.DropTargetDragEvent

graphics/api.gif
 

java.awt.dnd.DropTargetDropEvent

graphics/api.gif
 

Drag Sources

Now that you saw how to implement a program that contains a drop target, we want to show you how to implement a drag source.

The program in Example 7-21 fills a JList with all files in the current directory (see Figure 7-54.) The list component is a drag source. You can drag file items from the list component to any drop target that is willing to accept a list of files.

Figure 7-54. The DragSourceTest program

graphics/07fig54.gif
 

To turn a component into a drag source, you need to obtain a DragSource object—you can simply call the static DragSource.getDefaultDragSource method. Then, call the createDefaultDragGestureRecognizer method and supply it with:

For example,

DragSource dragSource = DragSource.getDefaultDragSource();
dragSource.createDefaultDragGestureRecognizer(component,
   DnDConstants.ACTION_COPY_OR_MOVE, dragGestureListener);

The DragGestureListener interface has a single method, dragGestureRecognized. The gesture recognizer calls that method as soon as it has noticed that the user wants to initiate a drag operation. In that method, you need to build the Transferable that the drop target will ultimately read in its drop method. Once you have assembled the Transferable, you call the startDrag method of the DragGestureEvent class. You supply an optional cursor, or null if you want to use the default drag cursor, followed by the Transferable and an object that implements the DragSourceListener interface. For example,

event.startDrag(null, transferable, dragSourceListener);

You need to do the usual busywork of defining a Transferable wrapper—see the code in the example program for details.

The drag source listener is notified repeatedly as the drag operation progresses. The interface has five methods:

void dragEnter(DragSourceDragEvent event)
void dragOver(DragSourceDragEvent event)
void dragExit(DragSourceEvent event)
void dropActionChanged(DragSourceDragEvent event)
void dragDropEnd(DragSourceDropEvent event)

You can use the first four methods to give the user visual feedback of the drag operation. However, generally, such feedback should be the role of the drop target. Only the last method, dragDropEnd, is very important. This method is called when the drop method has finished. For a move operation, you need to check whether the drop has succeeded. In that case, you need to update the drag source. (For a copy operation, you probably don't have to do anything.)

NOTE

graphics/note.gif
 

SDK 1.4 introduces a DragSourceAdapter helper class that implements all methods of the DragSourceListener interface as do-nothing methods. The sample program at the end of this section uses that class. If you use an earlier version of the SDK, you need to define the do-nothing methods yourself.

Here is the dragDropEnd method for our example program. When a move has succeeded, we remove the moved items from the list model.

public void dragDropEnd(DragSourceDropEvent event)
{
   if (event.getDropSuccess())
   {
      int action = event.getDropAction();
      if (action == DnDConstants.ACTION_MOVE)
      {
         for (int i = 0; i < draggedValues.length; i++)
            model.removeElement(draggedValues[i]);
      }
   }
}

In this method, we rely on the drop method to tell us what drop was actually carried out. Recall that the drop method can change a move action to a copy action if the source allowed both actions. The event.getDropAction of the DragSourceDropEvent class returns the action that the drop target reported when calling the acceptDrop method of the DropTargetDropEvent.

Try out the program in Example 7-21 and drag file items to various drop targets, such as the program in Example 7-20 or a native program such as Windows Explorer or WordPad.

NOTE

graphics/note.gif
 

When you try the dragging, you have to be careful that the drag gesture doesn't interfere with the normal mouse effects of the list control. Select one or more items. Press the mouse button on a selected item and move the mouse sideways, until it leaves the list component. Now the drag gesture is recognized. After the mouse has left the list component, press the SHIFT or CTRL key to modify the drop action.

CAUTION

graphics/caution.gif
 

The default drop action is a move. If you drag a file item from the list component and drop it into Windows Explorer, then Explorer moves the file into the target folder.

As you have seen, support for the system clipboard and the drag and drop mechanism are still very much a work in progress. The basics work, but, hopefully, future versions of the Java platform will offer more robust and comprehensive support.

In this section, we have covered the basic mechanics of the drag and drop mechanism. For more information, particularly about programming visual feedback, we recommend Core Swing: Advanced Programming by Kim Topley [Prentice Hall 1999].

Example 7-21 DragSourceTest.java
  1. import java.awt.*;
  2. import java.awt.datatransfer.*;
  3. import java.awt.dnd.*;
  4. import java.awt.event.*;
  5. import java.io.*;
  6. import java.util.*;
  7. import javax.swing.*;
  8.
  9. /**
 10.    This is a sample drag source for testing purposes. It consists
 11.    of a list of files in the current directory.
 12. */
 13. public class DragSourceTest
 14. {
 15.    public static void main(String[] args)
 16.    {
 17.       JFrame frame = new DragSourceFrame();
 18.      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 19.       frame.show();
 20.    }
 21. }
 22.
 23. /**
 24.    This frame contains a list of files in the current
 25.    directory with support for dragging files to a drop target.
 26.    Moved files are removed from the list.
 27. */
 28. class DragSourceFrame extends JFrame
 29. {
 30.    public DragSourceFrame()
 31.    {
 32.       setTitle("DragSourceTest");
 33.       setSize(WIDTH, HEIGHT);
 34.
 35.       Container contentPane = getContentPane();
 36.       File f = new File(".").getAbsoluteFile();
 37.       File[] files = f.listFiles();
 38.       model = new DefaultListModel();
 39.       for (int i = 0; i < files.length; i++)
 40.          try
 41.          {
 42.             model.addElement(files[i].getCanonicalFile());
 43.          }
 44.          catch (IOException exception)
 45.          {
 46.             JOptionPane.showMessageDialog(this, exception);
 47.          }
 48.       fileList = new JList(model);
 49.       contentPane.add(new JScrollPane(fileList),
 50.          BorderLayout.CENTER);
 51.       contentPane.add(new JLabel("Drag files from this list"),
 52.          BorderLayout.NORTH);
 53.
 54.       DragSource dragSource = DragSource.getDefaultDragSource();
 55.       dragSource.createDefaultDragGestureRecognizer(fileList,
 56.          DnDConstants.ACTION_COPY_OR_MOVE, new
 57.             DragGestureListener()
 58.             {
 59.                public void dragGestureRecognized(
 60.                   DragGestureEvent event)
 61.                {
 62.                   draggedValues = fileList.getSelectedValues();
 63.                   Transferable transferable
 64.                      = new FileListTransferable(draggedValues);
 65.                   event.startDrag(null, transferable,
 66.                      new FileListDragSourceListener());
 67.                }
 68.             });
 69.    }
 70.
 71.    /**
 72.       A drag source listener that removes moved
 73.       files from the file list.
 74.    */
 75.    private class FileListDragSourceListener
 76.       extends DragSourceAdapter
 77.    {
 78.       public void dragDropEnd(DragSourceDropEvent event)
 79.       {
 80.          if (event.getDropSuccess())
 81.          {
 82.             int action = event.getDropAction();
 83.             if (action == DnDConstants.ACTION_MOVE)
 84.             {
 85.                for (int i = 0; i < draggedValues.length; i++)
 86.                   model.removeElement(draggedValues[i]);
 87.             }
 88.          }
 89.       }
 90.    }
 91.
 92.    private JList fileList;
 93.    private DefaultListModel model;
 94.    private Object[] draggedValues;
 95.    private static final int WIDTH = 300;
 96.    private static final int HEIGHT = 200;
 97. }
 98.
 99. class FileListTransferable implements Transferable
100. {
101.    public FileListTransferable(Object[] files)
102.    {
103.       fileList = new ArrayList(Arrays.asList(files));
104.    }
105.
106.    public DataFlavor[] getTransferDataFlavors()
107.    {
108.       return flavors;
109.    }
110.
111.    public boolean isDataFlavorSupported(DataFlavor flavor)
112.    {
113.       return Arrays.asList(flavors).contains(flavor);
114.    }
115.
116.    public Object getTransferData(DataFlavor flavor)
117.       throws UnsupportedFlavorException
118.    {
119.       if(flavor.equals(DataFlavor.javaFileListFlavor))
120.          return fileList;
121.       else if(flavor.equals(DataFlavor.stringFlavor))
122.          return fileList.toString();
123.       else
124.          throw new UnsupportedFlavorException(flavor);
125.    }
126.
127.    private static DataFlavor[] flavors =
128.    {
129.       DataFlavor.javaFileListFlavor,
130.       DataFlavor.stringFlavor
131.    };
132.
133.    private java.util.List fileList;
134. }
java.awt.dnd.DragSource

graphics/api.gif
 

java.awt.dnd.DragGestureListener

graphics/api.gif
 

java.awt.dnd.DragGestureEvent

graphics/api.gif
 

java.awt.dnd.DragSourceListener

graphics/api.gif
 

java.awt.dnd.DragSourceDropEvent

graphics/api.gif
 

Data Transfer Support in Swing

Starting with SDK 1.4, Swing components have built-in support for data transfer that frees programmers from much of the burden of implementing copy and paste or drag and drop.

For example, start the TableSelectionTest program from Chapter 6 and highlight a range of cells. Then press CTRL+C and paste the clipboard contents into a text editor. The result is HTML-formatted text like this:

<html>
<table>
<tr>
  <th id=2>C
  <th id=3>D
  <th id=4>E
  <th id=5>F
<tr id=3>
  <td>12
  <td>16
  <td>20
  <td>24
. . .
</table>
</html>

If you add the line

table.setDragEnabled(true);

after the table constructor and recompile the program, then you can drag the selection area to drop targets. The drop target receives the table selection as HTML formatted data.

Table 7-6 summarizes the Swing components that are sources and targets for data transfer. The standard "Cut," "Copy," and "Paste" keyboard shortcuts are enabled for all components except the JColorChooser. Dragging is not enabled by default. You must call the setDragEnabled method to activate it.

Table 7-6. Data Transfer Support in Swing Components
Component Transfer source Transfer target
JFileChooser Exports file list N/A
JColorChooser Exports local reference to dolor object Accepts any color object

JTextField

JFormattedTextField

Exports selected text Accepts text
JPasswordField N/A (for security reasons) Accepts text

JTextArea

JTextPane

JEditorPane

Exports selected text Accepts text and file lists. Text is inserted. Files are opened.

JList

JLabel

JTree

Exports HTML description of selection N/A

The Swing package provides a potentially useful mechanism to quickly turn a component into a drop target. If the component has a method

void setName(Type t)

then you turn it into a drop target for data flavors with representation class Type simply by calling

component.setTransferHandler("name");

When a drop occurs, then the transfer handler checks whether one of the data flavors has representation class Type. If so, it invokes the setName method.

NOTE

graphics/note.gif
 

In JavaBeans terminology, the transfer handler sets the value of the name property. JavaBean properties are covered in Chapter 8.

For example, suppose you want to use drag and drop to change the background color of a text field. You need a transfer handler that invokes the

void setBackground(Color c)

method when a Color object is dragged onto the text field. Simply call

textField.setTransferHandler(new TransferHandler("background"));

Example 7-22 demonstrates this behavior. As you can see in Figure 7-55, the top of the frame contains a color chooser, and the bottom, a text field with the text "Drag color here." You need to drag the color from the inside of the "Preview" panel, not from one of the color swatches. When you drag it onto the text field, its background color changes.

Figure 7-55. The Swing Drag and Drop Test Program

graphics/07fig55.gif
 

CAUTION

graphics/caution.gif
 

By installing this transfer handler into the text field, you disable the standard transfer handler. You can no longer cut, copy, paste, drag, or drop text in the text field. A Swing component can only have one transfer handler.

Example 7-22 SwingDnDTest.java
 1. import java.awt.*;
 2. import javax.swing.*;
 3.
 4. /**
 5.    This program demonstrates how to easily add data transfer
 6.    capabilities to Swing components. Drag a color from the
 7.    "Preview" panel of the color chooser into the text field.
 8. */
 9. public class SwingDnDTest
10. {
11.    public static void main(String[] args)
12.    {
13.       JFrame frame = new SwingDnDFrame();
14.       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15.       frame.show();
16.    }
17. }
18.
19. /**
20.    This frame contains a color chooser and a text field. Dragging
21.    a color into the text field changes its background color.
22. */
23. class SwingDnDFrame extends JFrame
24. {
25.    public SwingDnDFrame()
26.    {
27.       setTitle("SwingDnDTest");
28.
29.       Container contentPane = getContentPane();
30.       JColorChooser chooser = new JColorChooser();
31.       chooser.setDragEnabled(true);
32.       contentPane.add(chooser, BorderLayout.CENTER);
33.       JTextField textField = new JTextField("Drag color here");
34.       textField.setDragEnabled(true);
35.       textField.setTransferHandler(
36.          new TransferHandler("background"));
37.       contentPane.add(textField, BorderLayout.SOUTH);
38.       pack();
39.    }
40. }
javax.swing.JComponent

graphics/api.gif
 

javax.swing.TransferHandler

graphics/api.gif
 

javx.swing.JFileChooser

graphics/api.gif
 

javax.swing.JColorChooser
javax.swing.JTextComponent
javax.swing.JList
javax.swing.JTable
javax.swing.JTree

 

CONTENTS